Home > Software design >  attempt to call a string value
attempt to call a string value

Time:10-28

Just trying to generate a series (loop of 10) random hexadecimal strings.. Here's my code

math.randomseed(os.time())

function genRanHex(length)
    genRanHex = ""
    for count = 1, length, 1 do
        num = math.random(0,15)
        genRanHex = genRanHex..string.upper(string.format("%x", num))
    end
    return genRanHex
end

for c = 1, 10, 1 do
    print(genRanHex(8))
end

getting the following error:

lua: main.lua:13: attempt to call a string value (global 'genRanHex') stack traceback: main.lua:13: in main chunk [C]: in ?

Thank you for any assistance

CodePudding user response:

Try using a different name for the function and local variable.

Better yet, add the local keyword to the variable declaration so that it's a local instead of a global.

CodePudding user response:

You're overwriting the global variable genRanHex that holds the function with the string genRanHex you're building in the function. The solution is to (1) localize everything and (2) use different names or (3) get rid of the inefficient string concatenation entirely. Here's how I would rewrite it, leveraging string.char to implicitly do the concat:

math.randomseed(os.time())

local function randomHexBytes(n)
    if n == 0 then return end
    return ("%X"):format(math.random(0, 0xF)):byte(), randomHexBytes(n-1)
end

local function genRanHex(n)
    return string.char(randomHexBytes(n))
end

for _ = 1, 10 do
    print(genRanHex(8))
end
  • Related