how to pass and receive value in Lua to another Lua?
Solution 1
Assign the value to the global table (_G
), like this:
_G.value = "Hello WOrld"
In another script, you can then do this:
value = _G.value
Solution 2
When you declare something local you are explicitly telling Lua NOT to share it between scripts. Just create a non-local variable instead:
value = "Hello World"
In b.lua File Simply Require the a.lua file and use it e.g In b.lua File
local a_File = require "a"
print(a_File.value)
You will get the output as
"Hello World"
Solution 3
better than just cramming stuff into the global table is to use lua's module system the way it was intended to be used.
say you had two files, a.lua and b.lua. b.lua needs some value from a.lua. this is how you'd accomplish that:
a.lua code:
module("a", package.seeall)
local myVal = "My value in file a"
local SomeVal = 15
function GetSomeValue()
return myVal
end
b.lua code:
require "a"
print(a.GetSomeValue()) -- prints 'My value in file a'
print(a.SomeVal) -- prints 15
print(SomeVal) -- prints nil, unless you've declared it in b.lua
this is MUCH cleaner than just stuffing things in the _G table. what happens if you have 3 or 4 different scripts, and you're trying to store values that should be named the same, just in different contexts? being able to say:
a.Value
a.Function()
is not only much more clear of where you are fetching data, but is much cleaner than saying
_G["Value"]
and hoping that that is actually the value you're hoping for. using _G might be easier if you're working on just a simple case with just two files. but it is better to learn the best practices and use them early. using _G would be a nightmare if you had several files working together cooperatively...
Solution 4
using director API we transfer a value to another lua file is easy. and it send data in table or array type
below code is usefull..
from a.lua file
data="hellow"
director:changeScene({data},"levelroom")
from b.lua file
module(...,package.seeall)
new=function(params)
localGroup=display.newGroup()
data=params.data
print(data) --output:hellow
return localGroup
end
gadss
Looking for the best motorcycle helmet reviews? I will guide you to choose the style that you want according to your needs. So let’s gear up! Also, it include reviews about the best motorcycle jackets, gloves, pants, boots, tire and other parts. It is for both men and women choice
Updated on June 04, 2022Comments
-
gadss almost 2 years
how can I pass a value from
a.lua
tob.lua
?let us say that in my
a.lua
i have this code of variable.local value = "Hello WOrld!" director:changeScene ("b")
my problem is that how can i pass
value
froma.lua
tob.lua
?thanks in advance....