[SOLVED] Attributing global function to table

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
pauls313
Citizen
Posts: 50
Joined: Tue Aug 02, 2016 3:07 am

[SOLVED] Attributing global function to table

Post by pauls313 »

I want my game to be very flexible, so no item will have fixed values. For example, a gun can work as if it were a sword. I wanted to do this by making a list of functions with each behavior

function crowbar()
...
end
function gun()
...
end

And then, I'd instantiate the items like this

item[1].func = gun()

So every frame I could run the item[1].func() so it would act like the behaviour of the function. But I'm not finding any way of doing this, all I saw were examples where you declared the function inside the table, not outside. Is there no other way?
Last edited by pauls313 on Sat Dec 09, 2017 10:08 pm, edited 1 time in total.
grump
Party member
Posts: 947
Joined: Sat Jul 22, 2017 7:43 pm

Re: Attributing global function to table

Post by grump »

Your example would work as intended if you assigned the actual function instead of the result of the function call to item[1].func

Code: Select all

item[1].func = gun -- no parentheses
Your also might want to look into a design pattern called Entity-Component-System.
User avatar
Beelz
Party member
Posts: 234
Joined: Thu Sep 24, 2015 1:05 pm
Location: New York, USA
Contact:

Re: Attributing global function to table

Post by Beelz »

Something like this?

Code: Select all


function crowbar()
	local item = {
		damage = 10,
		swingSpeed = .4
	}
	function item:use()
		-- do whatever
	end
	return item
end

-- then assign and use it
item[1] = crowbar()
item[1]:use()

Code: Select all

if self:hasBeer() then self:drink()
else self:getBeer() end
GitHub -- Website
pauls313
Citizen
Posts: 50
Joined: Tue Aug 02, 2016 3:07 am

Re: Attributing global function to table

Post by pauls313 »

grump wrote: Sat Dec 09, 2017 1:58 am Your example would work as intended if you assigned the actual function instead of the result of the function call to item[1].func

Code: Select all

item[1].func = gun -- no parentheses
Your also might want to look into a design pattern called Entity-Component-System.
That's perfect! Thanks.
Post Reply

Who is online

Users browsing this forum: No registered users and 81 guests