7

How to pass variable from another lua file? Im trying to pass the text variable title to another b.lua as a text.

a.lua

local options = {
    title = "Easy - Addition", 
    backScene = "scenes.operationMenu", 
}

b.lua

   local score_label_2 = display.newText({parent=uiGroup, text=title, font=native.systemFontBold, fontSize=128, align="center"})

2 Answers 2

4

There are a couple ways to do this but the most straightforward is to treat 'a.lua' like a module and import it into 'b.lua' via require

For example in

-- a.lua
local options =
{
  title = "Easy - Addition",
  backScene = "scenes.operationMenu",
}

return options

and from

-- b.lua
local options = require 'a'
local score_label_2 = display.newText
  {
    parent = uiGroup,
    text = options.title,
    font = native.systemFontBold,
    fontSize = 128,
    align = "center"
  }    
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, is it also possible if i assign multiple lua file to a single variable? For ex. local options = require 'a','c','d' ?
That probably wouldn't make much sense. What's being returned by require 'a' is whatever 'a.lua' is returning -- in this case, your local options in 'a.lua'. Just use a different variable name for each require you do.
-1

You can import the file a.lua into a variable, then use it as an ordinary table.

in b.lua

local a = require("a.lua")
print(a.options.title)

4 Comments

Please use the edit link explain how this code works and don't just give the code, as an explanation is more likely to help future readers. See also How to Answer. source
okay sir my bad.Thank you for the help, but is it also possible if i assign multiple lua file to a single variable? For ex. local a = require("a.lua","b.lua")
In order to assign multiple lua files, you may have to redefine the require keyword to support any number of arguments, like this: stackoverflow.com/questions/9145432/…, then all you have to do is to merge the tables, like this: stackoverflow.com/questions/1283388/lua-merge-tables.
The body of a.lua doesn't return anything so after local a = require("a.lua"), a would be nil

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.