i’m converting the Gilded Rose kata to Codea Lua just for fun. I wanted to directly convert puts item
to print(item)
but can’t see how to do it. i thought implementing Item:tostring would do it. i can of course implement Item:print but google won’t tell me how to override the built in print. is there a way?
thanks!
@RonJeffries What is the Gilded Rose kata. Without seeing what the code you’re trying to convert looks like, it’s hard to know what to do. puts item should just print item, so I don’t see why print(item) wouldn’t print item. That’s why I’m saying, without seeing any code that it’s hard to say why it doesn’t work.
sorry. for info on the kata, see my recent articles. it’s a refactoring exercise. includes a class named Item, and prints items in a horrid “test”.
calling print on a class instance in Codea just prints “table: 54568753” or whatever. i wanted to override it to print the fields. would i have to hammer the meta table to do that?
local item = Item("foo", 20) print(item)
where item init just saves those values as member vars
easy, of course to implement Item:print()
So if item is a class then here’s what I think without looking at anything.
PS. I’ll look at what you have in your articles.
function setup()
local item = Item("foo", 20)
print(item.name)
end
Item=class()
function Item:init(n,v)
self.name=n
self.value=v
end
@dave1707: the keyword override is confusing. I only understood what he wants after reading the :tostring
part.
@RonJeffries use print(json.encode(item))
which will convert the array to a readable string and print it into the console.
yes … i know some ways to explicitly code other than print(item), was looking to make print(item) just work. so far, fudging the metatable seems the only way …