[GMOD13] table.Random

[LUA]
local FNames = {}

if sex == true then
local FNames = {“Alice”, “Linzy”, “Susan”, “Mary”, “Linda”, “Helen”, “Sarah”, “Jessica”}
else
local FNames = {“James”, “John”, “Alan”, “Robert”, “Tony”, “Ryan”, “Dave”, “George”, “Charles”, “Edward”}
end

local LNames = {“Smith”, “Johnson”, “Williams”, “Jones”, “Brown”, “Davis”, “Miller”, “Wilson”, “Moore”, “Taylor”, “Anderson”, “Thomas”, “Jackson”, “White”}

return table.Random(FNames) … " " … table.Random(LNames)
[/LUA]

That code keeps generating this error for some reason,


bad argument #2 to 'random' (interval is empty)
lua/includes/extensions/table.lua:177

I checked the pages for upgrading your code, but I couldn’t find any reason why this isn’t working. I’ve either overlooked something or maybe it’s always been broken, ‘sex’ exists by the way. Any help or an explanation of what I’m doing wrong would be greatly appreciated.

Remove the local before FNames inside the if … else clause:
[LUA]
local FNames = {}

if sex == true then
FNames = {“Alice”, “Linzy”, “Susan”, “Mary”, “Linda”, “Helen”, “Sarah”, “Jessica”}
else
FNames = {“James”, “John”, “Alan”, “Robert”, “Tony”, “Ryan”, “Dave”, “George”, “Charles”, “Edward”}
end

local LNames = {“Smith”, “Johnson”, “Williams”, “Jones”, “Brown”, “Davis”, “Miller”, “Wilson”, “Moore”, “Taylor”, “Anderson”, “Thomas”, “Jackson”, “White”}

return table.Random(FNames) … " " … table.Random(LNames)
[/LUA]

The error comes because of the math.random receiving two values: 1 and 0. You can generate a value between 0 and 1, but not between 1 and 0, because then the range of it would be -1, and as we all know there are no straight lines with the length of -1 (ommiting vectors, but these aren’t lines anyway)

To further clarify, as I was about to rate you Dumb because I didn’t understand what you were talking about until I actually thought about the internal function calls.

You are getting this error because FNames is empty. You define FNames to be blank in Line 1, but never assign it. Instead you define a NEW table (Because of the Local keyword). Once you come out of the If statement, your local FNames is deleted, and your global FNames is still empty. The math.Random that is called in Table.Random assumes you have atleast 1 item in the table. Therefore, you are getting what he has stated: math.Random(1,0) which is out of bounds.

Hope that clarifies al-ryazanov’s explanation