Doridian / LuaJS

Lua VM running in Javascript (using emscripten)
Other
55 stars 10 forks source link

Instanciating JS classes? #29

Closed Frityet closed 9 months ago

Frityet commented 9 months ago

I get this error trying to instanciate a JS class

Error: TypeError: calling a builtin Map constructor without new is forbidden

Of course, I can make a simple JS wrapper to get around this, but is there a better way?

Frityet commented 9 months ago

I created this wrapper

function create(type, ...args) {
    return new type(...args);
}

but when I call it from lua:

local create = js.global.create
local map = create(window.Map)
console:log(map)

I get this error:

Error loading Lua script node 
<script type="text/lua" src="index.lua">
 Error: TypeError: type is undefined
    LuaError http://127.0.0.1:8080/luajs.js:1
    run http://127.0.0.1:8080/luajs.js:1
    __runNode http://127.0.0.1:8080/luajs.js:1
    __tryRunNode http://127.0.0.1:8080/luajs.js:1
    loadDocumentScripts http://127.0.0.1:8080/luajs.js:1
    enableLuaScriptTags http://127.0.0.1:8080/luajs.js:1
    <anonymous> http://127.0.0.1:8080/:2
    promise callback* http://127.0.0.1:8080/:2
luajs.js:1:15336
Frityet commented 9 months ago

ah nvm I needed to do window:create()

Doridian commented 9 months ago

@Frityet You can also already call constructors with LuaJS shims:

local map = js.global.Map:new()
js.global.console:log(map)
Frityet commented 9 months ago

@Frityet You can also already call constructors with LuaJS shims:


local map = js.global.Map:new()

js.global.console:log(map)

Thank you! Didn't know this, are there any more helpful utilities like that present?

Doridian commented 9 months ago

Not too many, really. You can call :toTable() on many JS objects to turn them into native Lua tables (but be careful, that can cause them to not work, depending on what they contain). There is js.eval (does exactly what one might think it does, avoid at all costs, eval ruins performance) and js.await (awaiting for async JS functions / Promises)