Loading external data into a function locally.

General discussion about LÖVE, Lua, game development, puns, and unicorns.
Post Reply
greenchile505
Prole
Posts: 2
Joined: Thu Jun 02, 2016 6:38 pm

Loading external data into a function locally.

Post 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
User avatar
zorg
Party member
Posts: 3465
Joined: Thu Dec 13, 2012 2:55 pm
Location: Absurdistan, Hungary
Contact:

Re: Loading external data into a function locally.

Post by zorg »

Hi and welcome to the forums! :3

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
Me and my stuff :3True Neutral Aspirant. Why, yes, i do indeed enjoy sarcastically correcting others when they make the most blatant of spelling mistakes. No bullying or trolling the innocent tho.
greenchile505
Prole
Posts: 2
Joined: Thu Jun 02, 2016 6:38 pm

Re: Loading external data into a function locally.

Post 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?
User avatar
Plu
Inner party member
Posts: 722
Joined: Fri Mar 15, 2013 9:36 pm

Re: Loading external data into a function locally.

Post 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.
Post Reply

Who is online

Users browsing this forum: No registered users and 0 guests