0

这是我修改以删除 module(..., package.seeall) 语句的演示。它效果很好,我想在 Corona sdk 项目中使用相同的想法。我想将一个值传递给我在演示中创建的现有变量。感谢您的任何建议。

main.lua----------------------------------------------------------- ---

-- Load external library (should be in the same folder as main.lua)
local testlib = require("testlib")
testlib.testvar = 100 -- Trying to change the testvar value in external module

-- cache same function, if you call more than once
local hello = testlib.hello

-- now all future invocations are "fast"
hello()


-- This all works fine, but I need to change the value of testvar.

testlib.lua ------------------------------------------------------------ ------

local M = {}
local testvar = 0 -- I need to change the value of this variable as well as others later.
print("testvar=",testvar)

local function hello()
    print ("Hello, module")
end
M.hello = hello

return M
4

1 回答 1

1

在这种情况下,Yourlocal testvar是您的模块 ( testlib.lua) 的私有变量。

您需要为该私有变量提供一些 setter/getter。

基本示例是将其添加到 Your testlib.lua

function setter(new_val)
    test_var = new_val
end

function getter()
    return test_var
end

M.set = setter
M.get = getter

现在,您可以在 Your中使用testlib.set("some new value..")and来操作变量的值。print(testlib.get())main.luatestvar

于 2013-09-18T23:11:34.463 回答