Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

override print of table?

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?



  • dave1707dave1707 Mod
    Posts: 8,739

    @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.

  • Posts: 806

    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?

  • edited May 2020 Posts: 806

    local item = Item("foo", 20)

    where item init just saves those values as member vars

    easy, of course to implement Item:print()

  • dave1707dave1707 Mod
    edited May 2020 Posts: 8,739

    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)
    function Item:init(n,v)
  • AnatolyAnatoly Mod
    Posts: 891

    @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.

  • Posts: 806

    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 ...

Sign In or Register to comment.