Bizzare "trying to invoke table value" in Lua

The following code snippet:

for weight, item in itemlist do weight_total=weight_total+weight end 

causes the error "attempt to call the table value" in the first line of this fragment. Why?

List of elements - a table of tables of weights and rows, for example:

 local itemlist = { {4,"weapon_pistol"}, {2,"weapon_357"}, ... 

Nothing is called as far as I can judge; why does this error occur?

+6
source share
1 answer

The general for expects 3 arguments: the value to be called, some value that is passed to it again, and the key in which the iteration should begin.
Stock lua does not call pairs for the first value passed to if if it is not callable, although some derivatives do.

So you should use ipairs(itemlist) , pairs(itemlist) , next, itemlist or whatever you want (the last two have the same behavior and are what most derivatives do).

An iterator unpacks a sequence of values ​​...

 function awesome_next(t, k) local k, v = next(t, k) if not v then return end return k, table.unpack(v) end for k, a, b, c, d in awesome_next, t do end 
+11
source

All Articles