Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds some documentation to public facing classes and functions #106

Merged
merged 7 commits into from
Jan 2, 2025
Merged
24 changes: 23 additions & 1 deletion src/engine.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { CreateEngineOptions } from './types'
import Global from './global'
import type LuaWasm from './luawasm'
import Thread from './thread'
Expand All @@ -20,7 +21,7 @@ export default class LuaEngine {
enableProxy = true,
traceAllocations = false,
functionTimeout = undefined as number | undefined,
} = {},
}: CreateEngineOptions = {},
) {
this.global = new Global(this.cmodule, traceAllocations)

Expand Down Expand Up @@ -55,20 +56,41 @@ export default class LuaEngine {
}
}

/**
* Executes Lua code from a string asynchronously.
* @param script - Lua script to execute.
* @returns A Promise that resolves to the result returned by the Lua script execution.
*/
public doString(script: string): Promise<any> {
return this.callByteCode((thread) => thread.loadString(script))
}

/**
* Executes Lua code from a file asynchronously.
* @async
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need to add @async with TSDoc

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Forgot to remove async

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please just remove this async and we are good to merge :)

* @param filename - Path to the Lua script file.
* @returns - A Promise that resolves to the result returned by the Lua script execution.
*/
public doFile(filename: string): Promise<any> {
return this.callByteCode((thread) => thread.loadFile(filename))
}

/**
* Executes Lua code from a string synchronously.
* @param script - Lua script to execute.
* @returns - The result returned by the Lua script.
*/
public doStringSync(script: string): any {
this.global.loadString(script)
const result = this.global.runSync()
return result[0]
}

/**
* Executes Lua code from a file synchronously.
* @param filename - Path to the Lua script file.
* @returns - The result returned by the Lua script.
*/
public doFileSync(filename: string): any {
this.global.loadFile(filename)
const result = this.global.runSync()
Expand Down
33 changes: 31 additions & 2 deletions src/factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,19 @@
import version from 'package-version'
import LuaEngine from './engine'
import LuaWasm from './luawasm'
import { EnvironmentVariables } from './types'
import { CreateEngineOptions, EnvironmentVariables } from './types'

/**
* Represents a factory for creating and configuring Lua engines.
*/
export default class LuaFactory {
private luaWasmPromise: Promise<LuaWasm>

/**
* Constructs a new LuaFactory instance.
* @param [customWasmUri] - Custom URI for the Lua WebAssembly module.
* @param [environmentVariables] - Environment variables for the Lua engine.
*/
public constructor(customWasmUri?: string, environmentVariables?: EnvironmentVariables) {
if (customWasmUri === undefined) {
const isBrowser =
Expand All @@ -21,10 +29,22 @@ export default class LuaFactory {
this.luaWasmPromise = LuaWasm.initialize(customWasmUri, environmentVariables)
}

/**
* Mounts a file in the Lua environment asynchronously.
* @param path - Path to the file in the Lua environment.
* @param content - Content of the file to be mounted.
* @returns - A Promise that resolves once the file is mounted.
*/
public async mountFile(path: string, content: string | ArrayBufferView): Promise<void> {
this.mountFileSync(await this.getLuaModule(), path, content)
}

/**
* Mounts a file in the Lua environment synchronously.
* @param luaWasm - Lua WebAssembly module.
* @param path - Path to the file in the Lua environment.
* @param content - Content of the file to be mounted.
*/
public mountFileSync(luaWasm: LuaWasm, path: string, content: string | ArrayBufferView): void {
const fileSep = path.lastIndexOf('/')
const file = path.substring(fileSep + 1)
Expand Down Expand Up @@ -54,10 +74,19 @@ export default class LuaFactory {
luaWasm.module.FS.writeFile(path, content)
}

public async createEngine(options: ConstructorParameters<typeof LuaEngine>[1] = {}): Promise<LuaEngine> {
/**
* Creates a Lua engine with the specified options.
* @param [options] - Configuration options for the Lua engine.
* @returns - A Promise that resolves to a new LuaEngine instance.
*/
public async createEngine(options: CreateEngineOptions = {}): Promise<LuaEngine> {
return new LuaEngine(await this.getLuaModule(), options)
}

/**
* Gets the Lua WebAssembly module.
PlaryWasTaken marked this conversation as resolved.
Show resolved Hide resolved
* @returns - A Promise that resolves to the Lua WebAssembly module.
*/
public async getLuaModule(): Promise<LuaWasm> {
return this.luaWasmPromise
}
Expand Down
46 changes: 44 additions & 2 deletions src/global.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,18 @@ interface LuaMemoryStats {
memoryMax?: number
}

/**
* Represents the global state of the Lua engine.
*/
export default class Global extends Thread {
private memoryStats: LuaMemoryStats | undefined
private allocatorFunctionPointer: number | undefined

/**
* Constructs a new Global instance.
* @param cmodule - The Lua WebAssembly module.
* @param shouldTraceAllocations - Whether to trace memory allocations.
*/
public constructor(cmodule: LuaWasm, shouldTraceAllocations: boolean) {
if (shouldTraceAllocations) {
const memoryStats: LuaMemoryStats = { memoryUsed: 0 }
Expand Down Expand Up @@ -59,6 +67,9 @@ export default class Global extends Thread {
}
}

/**
* Closes the global state of the Lua engine.
*/
public close(): void {
if (this.isClosed()) {
return
Expand All @@ -81,13 +92,22 @@ export default class Global extends Thread {
}
}

// To allow library users to specify custom types
// Higher is more important and will be evaluated first.
/**
* Registers a type extension for Lua objects.
PlaryWasTaken marked this conversation as resolved.
Show resolved Hide resolved
* Higher priority is more important and will be evaluated first.
* Allows library users to specify custom types
* @param priority - Priority of the type extension.
* @param extension - The type extension to register.
*/
public registerTypeExtension(priority: number, extension: LuaTypeExtension<unknown>): void {
this.typeExtensions.push({ extension, priority })
this.typeExtensions.sort((a, b) => b.priority - a.priority)
}

/**
* Loads a default Lua library.
* @param library - The Lua library to load.
*/
public loadLibrary(library: LuaLibraries): void {
switch (library) {
case LuaLibraries.Base:
Expand Down Expand Up @@ -124,13 +144,23 @@ export default class Global extends Thread {
this.lua.lua_setglobal(this.address, library)
}

/**
* Retrieves the value of a global variable.
* @param name - The name of the global variable.
* @returns - The value of the global variable.
*/
public get(name: string): any {
const type = this.lua.lua_getglobal(this.address, name)
const value = this.getValue(-1, type)
this.pop()
return value
}

/**
* Sets the value of a global variable.
* @param name - The name of the global variable.
* @param value - The value to set for the global variable.
*/
public set(name: string, value: unknown): void {
this.pushValue(value)
this.lua.lua_setglobal(this.address, name)
Expand All @@ -153,14 +183,26 @@ export default class Global extends Thread {
}
}

/**
* Gets the amount of memory used by the Lua engine. Can only be used if the state was created with the `traceAllocations` option set to true.
* @returns - The amount of memory used in bytes.
*/
public getMemoryUsed(): number {
return this.getMemoryStatsRef().memoryUsed
}

/**
* Gets the maximum memory allowed for the Lua engine. Can only be used if the state was created with the `traceAllocations` option set to true.
* @returns - The maximum memory allowed in bytes, or undefined if not set.
*/
public getMemoryMax(): number | undefined {
return this.getMemoryStatsRef().memoryMax
}

/**
* Sets the maximum memory allowed for the Lua engine. Can only be used if the state was created with the `traceAllocations` option set to true.
* @param max - The maximum memory allowed in bytes, or undefined for unlimited.
*/
public setMemoryMax(max: number | undefined): void {
this.getMemoryStatsRef().memoryMax = max
}
Expand Down
13 changes: 13 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,19 @@ export type LuaState = number

export type EnvironmentVariables = Record<string, string | undefined>

export interface CreateEngineOptions {
/** Injects all the lua standard libraries (math, coroutine, debug) */
openStandardLibs?: boolean
PlaryWasTaken marked this conversation as resolved.
Show resolved Hide resolved
/** Injects some JS objects to the Lua environment: Error, Promise, null, Objects */
injectObjects?: boolean
PlaryWasTaken marked this conversation as resolved.
Show resolved Hide resolved
/** Enables the proxy for JS objects, useful for classes, etc... */
enableProxy?: boolean
PlaryWasTaken marked this conversation as resolved.
Show resolved Hide resolved
/** Whether to trace memory allocations. */
traceAllocations?: boolean
/** Maximum time in milliseconds a Lua function can run before being interrupted. */
functionTimeout?: number
}

export enum LuaReturn {
Ok = 0,
Yield = 1,
Expand Down
5 changes: 3 additions & 2 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"incremental": false,
"moduleResolution": "node",
"inlineSources": false,
"removeComments": true,
"removeComments": false,
"sourceMap": false,
"target": "ES2018",
"skipLibCheck": true,
Expand All @@ -16,7 +16,8 @@
"noUnusedLocals": true,
"importHelpers": true,
"strict": true,
"resolveJsonModule": true
"resolveJsonModule": true,

},
"include": ["src/**/*", "test/**/*", "bench/**/*", "eslint.config.mjs"],
"exclude": ["node_modules"]
Expand Down