Pete
Pete

Reputation: 21

attempt to call a string value

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

Upvotes: 2

Views: 3234

Answers (2)

Luatic
Luatic

Reputation: 11171

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

Upvotes: 3

Dan Bonachea
Dan Bonachea

Reputation: 2477

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.

Upvotes: 1

Related Questions