Table.insert or (tablename).(object) = (value)

Whats the difference? Does table.insert only work for inserting another table in the table or can it store a value inside it like the second method in the title? And which one of the two is the best to use?

7 Likes

table.insert inserts an element into an array with optionally a position to place it at. Anything inserted into a table from table.insert has a numerical index. table.key = value is syntactic sugar for table[key] = value, which inserts the item into the array’s map. The latter can have numerical indexes or any other valid data type. table.insert isn’t restricted to inserting tables into other tables.

Determining which one you want to use is heavily based on the context of your code. I typically use table.insert if I don’t care about keys, while I use table[key] = value when the key matters.

local A = {}
table.insert(A, "B")
print(A[1]) --> B

local A = {}
A[1] = "B"
print(A[1]) --> B

local A = {}
A["C"] = "B"
print(A[1]) --> nil
print(A["C"]) --> B

Developer Hub on the table Library: table | Documentation - Roblox Creator Hub
Lua Manual on table.insert: Lua 5.1 Reference Manual
PiL on table.insert: Programming in Lua : 19.2

66 Likes

Thanks for your reply, i get it now. Was just wondering because i rarely use table.insert and didnt really know what was the difference. Thanks :slight_smile: good day.

4 Likes