Reputation: 22509
how can I pass a value from a.lua
to b.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
from a.lua
to b.lua
?
thanks in advance....
Upvotes: 3
Views: 15931
Reputation: 1092
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
Upvotes: 1
Reputation: 39014
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"
Upvotes: 9
Reputation: 14564
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...
Upvotes: 3
Reputation: 53351
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
Upvotes: 4