Hi, I was just wondering if there was a simple explanation to why only one of these statements work.
-- This works...
local a = {1, 2}
local n = a[math.random(1,2)]
-- But this doesn't?
local n = {1, 2}[math.random(1,2)]
Hi, I was just wondering if there was a simple explanation to why only one of these statements work.
-- This works...
local a = {1, 2}
local n = a[math.random(1,2)]
-- But this doesn't?
local n = {1, 2}[math.random(1,2)]
This happens because of how Lua (and Luau) handles table expressions.
In your first example:
local a = {1, 2}
local n = a[math.random(1,2)]
{1, 2} is stored in the variable a, making it persistent.a[math.random(1,2)], Lua properly retrieves a value from the existing table.However, in your second example:
local n = {1, 2}[math.random(1,2)]
{1, 2} is a temporary (anonymous) table, meaning it exists only for that moment.why does it work if you put the table in parentheses?
local n = ({1, 2})[math.random(1,2)]
When you write:
local n = {1, 2}[math.random(1,2)]
{1, 2} is an anonymous table created on the spot.However, when you wrap it in parentheses:
local n = ({1, 2})[math.random(1,2)]
{1, 2} as a full expression first.({1, 2}) as a table before trying to access an index, ensuring it works properly.Without parentheses, Lua might optimize away the table creation in weird ways. With parentheses, Lua fully creates the table first, then accesses it.
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.