6

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"})
Atilla Ozgur
  • 14,339
  • 3
  • 49
  • 69
Kilik Sky
  • 151
  • 1
  • 1
  • 12

2 Answers2

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"
  }    
greatwolf
  • 20,287
  • 13
  • 71
  • 105
  • Thank you, is it also possible if i assign multiple lua file to a single variable? For ex. local options = require 'a','c','d' ? – Kilik Sky Jan 09 '17 at 13:07
  • 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. – greatwolf Jan 09 '17 at 13:10
-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)
Burns
  • 146
  • 4
  • 2
    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 [answer]. [source](http://stackoverflow.com/users/5244995) – Jed Fox Jan 09 '17 at 11:15
  • 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") – Kilik Sky Jan 09 '17 at 13:05
  • In order to assign multiple lua files, you may have to redefine the `require` keyword to support any number of arguments, like this: http://stackoverflow.com/questions/9145432/load-lua-files-by-relative-path, then all you have to do is to merge the tables, like this: http://stackoverflow.com/questions/1283388/lua-merge-tables. – Burns Jan 09 '17 at 13:24
  • The body of a.lua doesn't return anything so after `local a = require("a.lua")`, `a` would be `nil` – Tom Blodget Jan 10 '17 at 01:37