TypeScriptToLua icon indicating copy to clipboard operation
TypeScriptToLua copied to clipboard

toString() ignored when defined as class variable

Open TheLartians opened this issue 7 years ago • 5 comments

Code

class A {
    toString = () => {
        return "A";
    }
}

console.log(new A()) 

Expected Output

A

Current Output

table: 0x28

TheLartians avatar Oct 01 '19 07:10 TheLartians

Would we also want to support this in that case?

const foo = { toString: () => 'foo' };
console.log(foo);

ark120202 avatar Oct 01 '19 11:10 ark120202

Is this really about translating console.log(x) to print(tostring(x)) instead of just print(x)? Or would we want to do some more logic there where we'd check if x.__tostring or x.tostring is not nil?

Perryvw avatar Oct 01 '19 16:10 Perryvw

Closing, since as was discussed in Discord it's too complex to support

ark120202 avatar Oct 09 '19 19:10 ark120202

I'd like to revisit it. We should either disallow non-method definitions of toString, or stop using prototype as a metatable and do something like

const test = {};
test.toString = () => 'Foo';
console.log(test);
local test = {}
__TS__Metatable(test).__tostring = function() return "Foo" end
print(test)

ark120202 avatar Feb 01 '20 22:02 ark120202

+1, I have a lua library object that has defined toString as a sort of a utility function

// Declare exposed API
declare const TestObject: {
    toString: (s: string) => string
}

// Use declared API in code
const x = TestObject.toString("hello");

compiles to

x = tostring(TestObject)

https://typescripttolua.github.io/play/#code/PTAEBEFMGMBsEMBOlSQB4AcD2BnSATUAQQAUBJAKHxgWVGiwDscAXUAFUlYHkAjAKxgsAXKADeFUFNAssAZRaIAlowDmogBQ5RrZWoCUoALwA+ULpWqKAXwoUQoAKp5Q1OEgLFyoFfSzUKBmY2NGMOLhY+QWgWADpZBT1VDQAiAAtIWFgsFP0AbiA

ohms-dev avatar Jul 17 '23 07:07 ohms-dev