Bizzare “attempt to call a table value” in Lua

孤街醉人 提交于 2019-12-01 14:13:49

问题


The following code snippet:

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

is causing the error "attempt to call table value" on the first line in that snippet. Why?

Itemlist is a table of tables of weights and strings, like such:

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

Nothing is being called as far as I can tell; why is this error coming up?


回答1:


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


来源:https://stackoverflow.com/questions/23350281/bizzare-attempt-to-call-a-table-value-in-lua

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!