【问题标题】:Can't declare table element with number from another table不能用另一个表中的数字声明表元素
【发布时间】:2013-08-17 01:19:16
【问题描述】:

代码非常简单。声明两个表,一个简单的和一个多维的:

Player = {X_Pos = 1, Y_Pos = 1, Current_Sprite_Num = 100}


    for j=1, Max_col_length do -- value ofMax_col_length doesn't matter here; positive integer anyway

        MapLayer_B[j] = {}

        for i=1, Max_row_length do --same here
            MapLayer_B[j][i] = 1
        end
    end

然后我尝试做这个操作:

MapLayer_B[Player[X_Pos]][Player[Y_Pos]] = Player[Current_Sprite_Num]

它应该替换MapLayer_BPlayer[Y_Pos]th 行表的Player[X_Pos]th 元素。相反,我在使用 LÖVE 编译器时遇到了这个错误:

  • 错误:尝试索引字段“?” (零值)

我真的不明白为什么会这样,因为MapLayer_BPlayer 表的所有元素都已声明,而不是保持为零。

有什么想法吗?

【问题讨论】:

    标签: arrays lua null lua-table love2d


    【解决方案1】:

    你需要使用Player.X_Pos而不是Player[X_Pos]等等。

    括号表示法会将“X_Pos”解释为变量,并尝试访问 taht 键(错误原因是未定义变量默认为 null)

    t = {a = 17}
    
    print( t.a ) --dot notation is simpler
    
    print( t["a"] ) --bracket notation expects a string
    
    key = "a" --that string can be from a variable
    print( t[key] )
    

    【讨论】:

    • 哦,这对我来说似乎是一个普遍的错误。我认为在 Lua 中,name.elementname[element] 相同。谢谢!
    猜你喜欢
    • 2012-12-29
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    相关资源
    最近更新 更多