【问题标题】:why is my global table being considered nil?为什么我的全局表被认为是零?
【发布时间】:2013-01-09 13:45:08
【问题描述】:

背景:

我正在尝试自学 Lua,但我很难理解为什么一个表在其中包含数据时被视为 nil。谁能帮我分析一下,为什么我从下面的代码 sn-p 中收到此错误消息?这是我的第一个程序之一,在开始我的实际项目之前,我真的需要了解这些概念。谢谢!

错误信息:

C:\Users\<user>\Desktop>lua luaCrap.lua
lua: luaCrap.lua:7: attempt to call global 'entry' (a nil value)
stack traceback:
        luaCrap.lua:7: in main chunk
        [C]: ?

代码:

--this creates the function to print
function fwrite (fmt, ...)
  return io.write(string.format(fmt, unpack(arg)))
end

--this is my table of strings to print
entry{
    title = "test",
    org = "org",
    url = "http://www.google.com/",
    contact = "someone",
    description = [[
                    test1
                    test2
                    test3]]
}

--this is to print the tables first value  
fwrite(entry[1])

--failed loop attempt to print table
-- for i = 1, #entry, 1 do
    -- local entryPrint = entry[i] or 'Fail'
    -- fwrite(entryPrint)
-- end

【问题讨论】:

    标签: printing lua runtime-error null lua-table


    【解决方案1】:

    你错过了条目分配。

    你需要把入口代码改成这样:

    entry = 
    {
        title = "test",
        org = "org",
        url = "http://www.google.com/",
        contact = "someone",
        description = [[
                        test1
                        test2
                        test3]]
    }
    

    为了澄清错误消息,在某些情况下假定使用括号,例如当您有一个直接跟在标签后面的表格时。解释器认为您正在尝试将一个表传递给一个名为entry 的函数,但它找不到该函数。它假设你真的是这个意思:

    entry({title = "test", ...})
    

    【讨论】:

    • 感谢您解决此问题。我真的看不出你的代码和我的代码有什么不同。只是括号 { 在新行上。是这样吗?
    • 不,您缺少赋值运算符=。我的例子包括它。
    • 谢谢!就在你写完之后,我看了我的条目,顿悟了,哈哈。 stackoverflow 说我必须再等 5 分钟才能接受你的回答。
    猜你喜欢
    • 1970-01-01
    • 2014-03-08
    • 2012-05-18
    • 2011-08-25
    • 1970-01-01
    • 2014-11-05
    • 2021-02-04
    • 2014-03-26
    • 2011-08-13
    相关资源
    最近更新 更多