Page 1 of 1
Loading external data into a function locally.
Posted: Tue Aug 23, 2016 5:51 pm
by greenchile505
Greetings,
I have an external file containing multiple Lua tables that I would like to only use as local tables in a function found in main.lua.
If I load them without 'local' in front of each table name, it works.
If I load them with 'local' in front of each table name, my function cannot see the data, no matter where I call the chunk with '()'.
I hope I am making sense.
Best regards,
PG
Re: Loading external data into a function locally.
Posted: Tue Aug 23, 2016 8:06 pm
by zorg
Hi and welcome to the forums!
Code: Select all
--yourfile.lua
local a,b,c = {},{},{}
-- define stuff to be inside the above tables
return function() unpack{a,b,c} end -- may only work with table.unpack, or maybe with both...
--main.lua
function something()
local t1,t1,t3 = require('yourfile')()
-- ...
end
Re: Loading external data into a function locally.
Posted: Tue Aug 23, 2016 8:26 pm
by greenchile505
Awesome. This makes sense. Thank you for the quick reply.
Question: Do I need to declare 'local' in both 'local a,b,c' (in my file) and 'local t1,t2,t3', (in 'main.lua')?
Seems redundant.. Does it matter?
Re: Loading external data into a function locally.
Posted: Tue Aug 23, 2016 9:49 pm
by Plu
Yeah. The first time you declare variables that are local to the file you have created. The second time you create variables that are local to the new function, which point to the same stuff.
It's kinda the same as doing this, where you'd also need to make them local twice:
Code: Select all
function pretend_this_is_a_file()
local a, b = 1, 2
return a, b
end
function pretend_this_is_your_loader()
local a, b = pretend_this_is_a_file()
end
If you don't declare it local in both scopes, it's going to leak into the global scope.