Calling a function with a string

Hello!

I am trying to build a table with items inside and items can have special effects, so I thought I could store funciton name as string and call it when needed

How can I do it?

Functions are first class citizens in Lua. You can store functions in a table if you want to. Like this:

local function cut(target)
	target.hp = target.hp - 7
	target.bleeding = true
	print(target.name .. " takes damage and starts bleeding!")
end

local function crush(target)
	target.hp = target.hp - 4
	target.confused = true
	print(target.name .. " takes damage and becomes confused!")
end

local function burn(target)
	target.burning = true
	print(target.name .. " is on fire!")
end


local items = {
	broadsword = {
		name = "Broadsword",
		effects = { cut },
		cost = 150,
	},
	flaming_sword = {
		name = "Flaming sword",
		effects = { cut, burn },
		cost = 3000,
	},
	club = {
		name = "Club",
		effects = { crush },
		cost = 30,
	}
}

local function attack(attacker, target)
	print(attacker.name .. " attacks " .. target.name)
	for _,effect in pairs(attacker.weapon.effects) do
		effect(target)
	end
end

local player = {
	hp = 20,
	name = "Hero",
	weapon = items.flaming_sword,
}

local goblin = {
	hp = 10,
	name = "Goblin",
	weapon = items.club,
}

attack(player, goblin)
print(goblin.hp)

Will output:

Hero attacks Goblin
Goblin takes damage and starts bleeding!
Goblin is on fire!
3
5 Likes

:open_mouth: ok incredible, Lua will always surprise me!

thank you for quick answer!

1 Like

uh… didnt know that in that way. quite that easy!

1 Like