Why does only one of these work?

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)]
2 Likes

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)]
  • The table {1, 2} is stored in the variable a, making it persistent.
  • When you index 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.
  • Lua doesn’t store it anywhere, and depending on optimizations, it might get discarded before indexing happens.
1 Like

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.
  • Lua doesn’t store it anywhere before trying to index it, which can cause issues.

However, when you wrap it in parentheses:

local n = ({1, 2})[math.random(1,2)]
  • The parentheses force Lua to evaluate {1, 2} as a full expression first.
  • Now, Lua treats ({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.

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.