为什么我的全局表被视为nil?

背景:

我正在尝试自学 Lua,但在理解为什么一个表格在其中包含数据时被视为 nil 时遇到了困难。有人能为我分解一下下面代码片段中为什么我会得到这个错误消息吗?这是我第一个程序之一,我真的需要在开始我的真正项目之前掌握这些概念。谢谢!

错误消息:

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
点赞
用户1208078
用户1208078

你没有给entry赋值。

你需要将entry的代码改为以下内容:

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

为了澄清错误消息,括号在某些情况下被假定存在,例如在一个标签直接后面跟着一个表格时。解释器认为您正在尝试将表格传递给一个名为 entry 的函数,但它找不到该函数。它假定您实际上想要这样做:

entry({title = "test", ...})
2013-01-25 15:04:02