Search code examples
lualua-table

Lua table.insert did not work


So recently I made this code where ill call a function to insert the data into the table, however it did not insert the data but does not return any errors, any problem with this?

datas = {}
function AddInfo(Name,Desc,dataser,Func)
table.insert(datas,{Name,Desc,dataser,Func})
end
for i,v in pairs(datas) do
print(i)
end
AddInfo("hw","Print Hello World to console","stringer",function()
print("Hello World")
end)

Solution

  • It does insert into the datas table. However, you are printing before the AddInfo gets called. Place your for i, v... loop after the AddInfo had a chance to run; and you'll get your desired insert operation result:

    datas = {}
    function AddInfo(Name,Desc,dataser,Func)
      table.insert(datas,{Name,Desc,dataser,Func})
    end
    
    AddInfo("hw","Print Hello World to console","stringer",function()
      print("Hello World")
    end)
    
    for i,v in pairs(datas) do
      print(i, v)
    end