Bizzare “attempt to call a table value” in Lua

前端 未结 1 1914
余生分开走
余生分开走 2021-01-17 11:14

The following code snippet:

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

is causing the error \"attempt to call

相关标签:
1条回答
  • 2021-01-17 11:52

    The generic for expects 3 arguments: a callable value, some value which is repeatedly passed to it, and the key where the iteration shall start.
    Stock lua does not call pairs on the first value passed to for if that's not callable, though some derivatives do.

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

    As an example, an iterator unpacking the value sequence:

    function awesome_next(t, k)
        k, t = next(t, k)
        if not t then return end
        return k, table.unpack(t)
    end
    
    for k, a, b, c, d in awesome_next, t do
    end
    
    0 讨论(0)
提交回复
热议问题