【问题标题】:How to get a variable from a script to other script in corona sdk (Lua)如何在corona sdk(Lua)中从脚本获取变量到其他脚本
【发布时间】:2020-01-28 23:57:01
【问题描述】:

我想从 main.lua 之类的脚本中获取一个变量并将其发送到 menu.lua

【问题讨论】:

  • 这两个脚本有什么关系? main 是否导入 menu

标签: variables lua coronasdk


【解决方案1】:

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

全局变量

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

你的项目/main.lua

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

你的项目/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( ... )中传递参数

这是 Corona 推荐的方式。见Scene Optionshttps://docs.coronalabs.com/api/library/composer/gotoScene.html

你的项目/main.lua

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

你的项目/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 共享信息的另一种方式,请在 cmets 中询问我。我很高兴添加到这篇文章中。

【讨论】:

    猜你喜欢
    • 2015-02-19
    • 1970-01-01
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-02
    • 1970-01-01
    • 2022-12-04
    相关资源
    最近更新 更多