I'm looking for a nice way to do a map / select on a Lua table.
eg. I have a table :
myTable = {
pig = farmyard.pig,
cow = farmyard.bigCow,
sheep = farmyard.whiteSheep,
}
How do I write myTable.map(function(f) f.getName)? [Assuming all farmyard animals have names]
ie. apply the function to all elements in the table.
write your own version? there isn't a built-in function to do this in lua.
function map(tbl, f)
local t = {}
for k,v in pairs(tbl) do
t[k] = f(v)
end
return t
end
t = { pig = "pig", cow = "big cow", sheep = "white sheep" }
local newt = map(t, function(item) return string.upper(item) end)
table.foreach(t, print)
table.foreach(newt, print)
produces:
pig pig
sheep white sheep
cow big cow
pig PIG
cow BIG COW
sheep WHITE SHEEP
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With