[Solved] Require and local functions

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
User avatar
Helvecta
Party member
Posts: 167
Joined: Wed Sep 26, 2012 6:35 pm

[Solved] Require and local functions

Post by Helvecta »

I'm having a little trouble figuring out how to store local functions on files that are required. I'm not sure how to word this, so I wrote some scripts to explain what I mean (also attached as a .zip):

main.lua

Code: Select all

function love.load()
	foobar = require 'foobar'
	foobar.foo()
end
foobar.lua

Code: Select all

local foo = {}

function foo.foo()
	bar()
end

local function bar()
	assert(nil, "foobar!")
end

return foo
Maybe this is already obvious but foo.foo() will return an error because it refers to bar() - a function that is local to foobar.lua. require would just scurry past it, but I'd like to keep it local because the main script has no direct use for bar, only the foo table would. Is there any way to retain this type of structure, keep the function local and make everything work? If not, could I get some alternate ways to make this work (preferably while keeping bar a local function)?
Attachments
Katanafoobari.zip
(352 Bytes) Downloaded 89 times
Last edited by Helvecta on Sat Mar 08, 2014 2:17 am, edited 1 time in total.
User avatar
Xgoff
Party member
Posts: 211
Joined: Fri Nov 19, 2010 4:20 am

Re: Require and local functions

Post by Xgoff »

yes

just move the definition of bar() above that of foo.foo(). this will turn foo.foo() into a closure with bar() as an upvalue, which allows it to be used by foo.foo() even though it is no longer in scope by the time you call it
User avatar
Helvecta
Party member
Posts: 167
Joined: Wed Sep 26, 2012 6:35 pm

Re: Require and local functions

Post by Helvecta »

-- :ultrashocked: WH..

Well that was simple. I'm just gonna, go over here and reevaluate my abilities as a programmer now.

Thanks for the help!
Post Reply

Who is online

Users browsing this forum: Google [Bot] and 144 guests