table.Random error

[lua]
function whatsmyname()
print("Your name could possibly be “…table.Random(names)…” ")
end

names={
“Mic”,
“Tom”,
“Mac”,
“Jon”,
“Sue”,
“BITCH”
}

whatsmyname()
[/lua]

I get this error:



lua: blank lua file.lua:21: attempt to call field 'Random' (a nil value)


Just made me wonder :aaaaa:

The names table should be placed above the whatsmyname function.

[lua]
names={
“Mat”,
“Tom”,
“Mac”,
“Jon”,
“Sue”,
“BITCH”
}

function whatsmyname()
print("Your name could possibly be “…table.Random(names)…” ")
end

whatsmyname()
[/lua]
Still getting


lua: blank lua file.lua:31: attempt to call field 'Random' (a nil value)

Have you overridden the global variable table anywhere?

No.

Tthat only matters if the names table was local. He made it global (a different mistake). Try it with a less generic name, call it myfunction_names or something because it’s quite possible that another script could interfere with a simple name like that.

if this is what you mean:
[lua]
myfunction_names={
“Mat”,
“Tom”,
“Mac”,
“Jon”,
“Sue”,
“BITCH”
}

print(“Your name is “…table.Random…”!!!”)
[/lua]
Then I still get this error.


lua: test.lua:10: attempt to concatenate field 'Random' (a nil value)

Are you testing this in the lua standalone interpreter? table.Random is unique to gmod lua so it won’t work outside of the game.

If you are you could use a function like this to replicate it’s functionality :
(Untested)
[lua]function tablerandom(t)
return t[1,#t]
end[/lua]

Do you mean
[lua]function tablerandom(t)
return t[math.random(1,#t)]
end[/lua]or is there a feature of tables that wasn’t mentioned in PIL.

You’re doing the table.Random wrong. You put table.Random, it should be table.Random(myfunction_names)

That wouldn’t give him that error message though, he’d just end up with function:<address> in his string.
The error message is saying that the table library doesn’t have the Random function in it.

Let’s try something else.

print(table)
PrintTable(table)

Let’s find out just what happened to the table library.

You are right, I was tired. :slight_smile:

I already answered, he is testing in the lua standalone interpreter. That is why he doesn’t have the table.Random function.

Yep, sorry everyone I didn’t know table.Random was gmod specific :open_mouth:

Usually the functions in table that start with a capital letter are gmod specific (haven’t check thoroughly, it just appears that way to me) and the ones that start with a lowercase letter are included in Lua itself.

Yes, as far as I know that is true for all GMod functions.

Now I feel motivated to create a table.Random function with my Lua interpreter :downsrim: