如何从脚本获取变量到 corona sdk 中的其他脚本 (Lua)

How to get a variable from a script to other script in corona sdk (Lua)

我想得到一个我用 main.lua 之类的脚本创建的变量,并将其发送到 menu.lua

有很多方法可以做到这一点。我给你两个。

全局变量

可能是最简单的方法,但也会很快变得混乱。

your-project/main.lua

--
-- main.lua
--
myVariableFromMain1 = "hello world"
myVariableFromMain2 = "another sample variable"
composer.gotoScene( "menu" )

your-project/menu.lua

--
-- menu.lua
--
local composer = require( "composer" )
local scene = composer.newScene()
function scene:create( event )
    local sceneGroup = self.view
    print(myVariableFromMain1) -- prints "hello world!"
    print(myVariableFromMain2) -- prints "another sample variable"
end
scene:addEventListener( "create", scene )
return scene

composer.gotoScene( ... )

中传递一个参数

这是科罗娜推荐的方式。请参阅 https://docs.coronalabs.com/api/library/composer/gotoScene.html

中的 Scene Options

your-project/main.lua

--
-- main.lua
--
composer.gotoScene( "menu", { params = {
    myVariableFromMain1 = "hello world!",
    myVariableFromMain2 = "another sample variable"
}} )

your-project/menu.lua

--
-- menu.lua
--
local composer = require( "composer" )
local scene = composer.newScene()
function scene:create( event )
    local sceneGroup = self.view
    print(myVariableFromMain) -- prints "hello world!"
end
scene:addEventListener( "create", scene )
return scene

如果您想了解 menu.luamain.lua 共享信息的另一种方式,请在评论中询问我。我很高兴添加到此 post。