Skip to content

lde-org/lua-sys

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

29 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

lua-sys

Bindings for the Lua C Api (specifically LuaJIT) for lde.

It adds both a raw api (accessible via require("lua-sys").raw) which are raw bindings to the C api practically verbatim, alongside a higher level api that abstracts away the stack based Lua api for more idiomatic usage.

Why is this useful?

For creation of isolated lua states that you can sandbox properly rather than running lua code and attempting to sandbox it via fenv/debug.sethook/etc isolation.

Also, allows sandboxed scripts to not affect your main lua state's ffi bindings.

Usage

lde add lua-sys --git https://github.com/lde-org/lua-sys

Example

local lua = require("lua-sys")

local state = lua.new()

-- Load compiles code into a Chunk. Use :eval() to run it and get a Value.
local fn = state:load("return function(a, b) return a + b end"):eval()
local result = fn:call(3, 4)
print(result:type())  --> "number"
print(result:value()) --> 7

-- :exec() runs a chunk for side effects, discarding results.
state:load("answer = 42"):exec()
local answer = state:load("return answer"):eval()
print(answer:value()) --> 42

-- Access the global table
local globals = state:globals()
globals:set("message", "hello from Lua")
local msg = globals:get("message")
print(msg:type())  --> "string"
print(msg:value()) --> "hello from Lua"

-- Pass plain Lua functions as callbacks
globals:set("greet", function(name)
  return "Hi, " .. name:value()
end)

local greet = state:load("return function(n) return greet(n) end"):eval()
print(greet:call("World"):value()) --> "Hi, World"

state:close()

Example (Raw)

local raw = require("lua-sys").raw

local L = raw.lnewstate()
raw.openlibs(L)

-- Compile and run a Lua chunk
raw.loadstring(L, "return 2 + 2")
raw.pcall(L, 0, 1, 0) -- (state, nargs, nresults, errfunc)
print(raw.tonumber(L, 1)) --> 4

-- Push values, manipulate the stack
raw.pushstring(L, "hello")
raw.pushnumber(L, 42)
print(raw.tolstring(L, 1)) --> "hello"
print(raw.gettop(L))        --> 2

-- Work with tables
raw.createtable(L, 0, 0)
raw.pushstring(L, "value")
raw.setfield(L, 1, "key")
raw.getfield(L, 1, "key")
print(raw.tolstring(L, 2)) --> "value"

raw.close(L)

About

LuaJIT C Api bindings for LuaJIT

Topics

Resources

Stars

Watchers

Forks

Contributors

Languages