expose loadLib

pull/6/head
Teoxoy 6 years ago
parent 3d6f35a579
commit e45eda2b71

@ -56,6 +56,25 @@ luaEnv.runfile('somefile.lua')
`runfile` uses `config.fileExists` and `config.loadFile`
### Create a global library
Creating a global library allows you write APIs that you can use in the Lua environment.
```js
function helloBuilder(name) {
const NAME = luainjs.utils.coerceArgToString(name, 'sayHi', 1)
return `Hello ${NAME}!`
}
const myLib = new luainjs.Table({ helloBuilder })
luaEnv.loadLib('myLib', myLib)
const helloStr = luaEnv.run(`return myLib.helloBuilder('John')`)
console.log(helloStr)
```
Check out the [math lib](./src/lib/math.ts) for a more extensive example.
## Example
Check out the [test runner](./tests/test.js) for a concrete example.

@ -1,3 +1,5 @@
/* eslint-disable import/order */
/* eslint-disable import/no-duplicates */
import { Scope } from './Scope'
import { createG } from './lib/globals'
import { operators } from './operators'
@ -49,6 +51,7 @@ function createEnv(
): {
run: (script: string) => LuaType
runfile: (path: string) => LuaType
loadLib: (name: string, value: Table) => void
} {
const cfg: Config = {
LUA_PATH: './?.lua',
@ -65,17 +68,17 @@ function createEnv(
)
const loaded = libPackage.get('loaded') as Table
const load = (name: string, value: Table): void => {
const loadLib = (name: string, value: Table): void => {
_G.rawset(name, value)
loaded.rawset(name, value)
}
load('_G', _G)
load('package', libPackage)
load('math', libMath)
load('table', libTable)
load('string', libString)
load('os', getLibOS(cfg))
loadLib('_G', _G)
loadLib('package', libPackage)
loadLib('math', libMath)
loadLib('table', libTable)
loadLib('string', libString)
loadLib('os', getLibOS(cfg))
_G.rawset('require', _require)
@ -91,8 +94,11 @@ function createEnv(
return {
run,
runfile
runfile,
loadLib
}
}
export { createEnv }
// eslint-disable-next-line import/first
import * as utils from './utils'
export { createEnv, Table, LuaError, utils }

@ -26,4 +26,18 @@ let exitCode = 0
luaEnv.runfile('bwcoercion.lua')
}
{
const luaEnv = luainjs.createEnv()
function helloBuilder(name) {
const NAME = luainjs.utils.coerceArgToString(name, 'sayHi', 1)
return `Hello ${NAME}!`
}
const myLib = new luainjs.Table({ helloBuilder })
luaEnv.loadLib('myLib', myLib)
const str = luaEnv.run(`return myLib.helloBuilder('John')`)
if (str !== 'Hello John!') {
throw Error("Strings don't match!")
}
}
process.exit(exitCode)

Loading…
Cancel
Save