Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Module Corona sdk将值从main.lua传递到外部模块_Module_Lua_Coronasdk - Fatal编程技术网

Module Corona sdk将值从main.lua传递到外部模块

Module Corona sdk将值从main.lua传递到外部模块,module,lua,coronasdk,Module,Lua,Coronasdk,下面是我修改的一个演示,它删除了module(…,package.seeall)语句。它工作得很好,我想在Corona sdk项目中使用相同的想法。我想将一个值传递给我在演示中创建的现有变量。谢谢你的建议 梅因·卢阿-------------------------------------------------- -- Load external library (should be in the same folder as main.lua) local testlib = require

下面是我修改的一个演示,它删除了module(…,package.seeall)语句。它工作得很好,我想在Corona sdk项目中使用相同的想法。我想将一个值传递给我在演示中创建的现有变量。谢谢你的建议

梅因·卢阿--------------------------------------------------

-- 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.
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
testlib.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.
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

在这种情况下,
localtestvar
是模块的私有变量(
testlib.lua

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

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

function setter(new_val)
    test_var = new_val
end

function getter()
    return test_var
end

M.set = setter
M.get = getter

现在,您可以在
main.lua
中使用
testlib.set(“一些新值”)
print(testlib.get())
来操作
testvar
变量的值。

谢谢您的建议。我试过了。由于某些原因,在setter中分配的任何内容在getter函数中都返回nil。@jadkins4,它不能作为
main.lua
的不同实例或lua VM的不同实例之间的交换。如果我没弄错的话…只有一个main.lua的实例。我试图将一个值传递给外部模块testlib.lua。我已经在testlib.lua的顶部声明了test_var变量,当我在testlib.lua内执行函数时,需要将其更改为不同的值。我并不真正需要返回main.lua的值,但是当我在setter函数外部的testlib.lua内部打印setter的值时,它返回nil。我试着让它全球化,但仍然是零。