MCPcopy Create free account
hub / github.com/ceifa/wasmoon / ErrorTypeExtension

Class ErrorTypeExtension

src/type-extensions/error.ts:7–77  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

5import { LuaReturn, LuaState } from '../types'
6
7class ErrorTypeExtension extends TypeExtension<Error> {
8 private gcPointer: number
9
10 public constructor(thread: Global, injectObject: boolean) {
11 super(thread, 'js_error')
12
13 this.gcPointer = thread.lua.module.addFunction((functionStateAddress: LuaState) => {
14 // Throws a lua error which does a jump if it does not match.
15 const userDataPointer = thread.lua.luaL_checkudata(functionStateAddress, 1, this.name)
16 const referencePointer = thread.lua.module.getValue(userDataPointer, '*')
17 thread.lua.unref(referencePointer)
18
19 return LuaReturn.Ok
20 }, 'ii')
21
22 if (thread.lua.luaL_newmetatable(thread.address, this.name)) {
23 const metatableIndex = thread.lua.lua_gettop(thread.address)
24
25 // Mark it as uneditable
26 thread.lua.lua_pushstring(thread.address, 'protected metatable')
27 thread.lua.lua_setfield(thread.address, metatableIndex, '__metatable')
28
29 // Add the gc function
30 thread.lua.lua_pushcclosure(thread.address, this.gcPointer, 0)
31 thread.lua.lua_setfield(thread.address, metatableIndex, '__gc')
32
33 // Add an __index method that returns the message field
34 thread.pushValue((jsRefError: Error, key: unknown) => {
35 if (key === 'message') {
36 return jsRefError.message
37 }
38 return null
39 })
40 thread.lua.lua_setfield(thread.address, metatableIndex, '__index')
41
42 // Add a tostring method that returns the message.
43 thread.pushValue((jsRefError: Error) => {
44 // The message rather than toString to avoid the Error: prefix being
45 // added. This fits better with Lua errors.
46 return jsRefError.message
47 })
48 thread.lua.lua_setfield(thread.address, metatableIndex, '__tostring')
49 }
50 // Pop the metatable from the stack.
51 thread.lua.lua_pop(thread.address, 1)
52
53 if (injectObject) {
54 // Lastly create a static Promise constructor.
55 thread.set('Error', {
56 create: (message: string | undefined) => {
57 if (message && typeof message !== 'string') {
58 throw new Error('message must be a string')
59 }
60
61 return new Error(message)
62 },
63 })
64 }

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected