尝试索引local(布尔值)

And*_*gon 5 lua coronasdk

我有2个不同的Lua文件,main.luagame_model.lua.我正在尝试在JSON文件中保存一些细节(我用谷歌搜索使用JSON文件将是保存用户设置和得分的最佳方式),但我收到以下错误:

错误:文件:main.lua行:11尝试索引本地'游戏'(布尔值)

为什么我会收到此错误以及如何解决?

这是我的代码main.lua:

--Main.lua

display.setStatusBar( display.HiddenStatusBar )

local composer = require( "composer" )
local game = require("data.game_model")

myGameSettings = {}
myGameSettings.highScore = 1000
myGameSettings.soundOn = true
myGameSettings.musicOff = true
myGameSettings.playerName = "Andrian Gungon"
game.saveTable(myGameSettings, "mygamesettings.json")

composer.gotoScene("scripts.menu")
Run Code Online (Sandbox Code Playgroud)

game_model.lua(在data子目录中)包含以下代码:

--game_model.lua (located at data/game_model.lua)

local json = require("json")

function saveTable(t, filename)
    local path = system.pathForFile( filename, system.DocumentsDirectory)
    local file = io.open(path, "w")
    if (file) then
        local contents = json.encode(t)
        file:write( contents )
        io.close( file )
        return true
    else
        print( "Error!" )
        return false
    end
end

function loadTable(filename)
    local path = system.pathForFile( filename, system.DocumentsDirectory)
    local contents = ""
    local myTable = {}
    local file = io.open( path, "r" )
    if (file) then         
         local contents = file:read( "*a" )
         myTable = json.decode(contents);
         io.close( file )
         return myTable 
    end
    return nil
end
Run Code Online (Sandbox Code Playgroud)

lhf*_*lhf 11

这意味着模块data.game_model在加载时没有返回任何内容.
在这种情况下,require返回true.


Goo*_*reg 7

要解决lhf 的答案中指出的问题,您可以将表保存和加载函数放入由 返回的表中data.game_model,如下所示:

-- Filename: data/game_model.lua

local model = {}

local json = require("json")

function model.saveTable( t, filename )
    -- code for saving
end

function model.loadTable( filename )
    -- code for loading
end

return model
Run Code Online (Sandbox Code Playgroud)

另请注意,一个常见的错误是将函数声明为而model:saveTable( t, fn )不是model.saveTable( t, fn )。请记住,前者是 的语法糖model.saveTable( model, t, fn )

现在变量gameinlocal game = require( "data.game_model" )应该被初始化为包含函数的表。您可以轻松检查:

local game = require("data.game_model")

print( type( game ) )
for k,v in pairs(game) do
    print(k,v)
end 
Run Code Online (Sandbox Code Playgroud)

产生如下输出:

table
loadTable   function: 0x7f87925afa50
saveTable   function: 0x7f8794d73cf0
Run Code Online (Sandbox Code Playgroud)