Examples
Straight from the Lua reference manual and Luak's own embedding surface. Nothing here relies on an unreleased feature.
Hello, world
The smallest possible Luak embedding: load a chunk, call it.
import org.basaltmc.luak.lib.LuaPlatform
val globals = LuaPlatform.standardGlobals()
globals.load("print('hello, world')")!!.call()
Coroutines
create, resume and yield, exactly as specified by Lua.
local co = coroutine.create(function(a, b)
print("start", a, b)
local c = coroutine.yield(a + b)
print("resume", c)
end)
print(coroutine.resume(co, 1, 2))
print(coroutine.resume(co, 10))
Tables and metatables
The pattern behind every object system built on top of Lua.
local Animal = {}
Animal.__index = Animal
function Animal.new(name)
return setmetatable({ name = name }, Animal)
end
function Animal:speak()
print(self.name .. " makes a sound.")
end
local cat = Animal.new("Whiskers")
cat:speak()
Sandboxing
Load only the libraries a script actually needs, by hand, instead of the full standard set.
import org.basaltmc.luak.Globals
import org.basaltmc.luak.lib.BaseLib
import org.basaltmc.luak.lib.StringLib
import org.basaltmc.luak.lib.TableLib
// A Globals with no io, no os, no package.loadlib: safe to hand a script author.
val globals = Globals()
globals.load(BaseLib())
globals.load(TableLib())
globals.load(StringLib())
Calling back into Kotlin
Expose a Kotlin function as a Lua global, the same way the base library does internally.
import org.basaltmc.luak.LuaValue
import org.basaltmc.luak.lib.LuaPlatform
import org.basaltmc.luak.lib.OneArgFunction
val globals = LuaPlatform.standardGlobals()
globals.set("greet", object : OneArgFunction() {
override fun call(arg: LuaValue?): LuaValue? =
LuaValue.valueOf("Hello from Kotlin, ${'$'}{arg?.tojstring()}!")
})
globals.load("print(greet('Luak'))")!!.call()
Want to try one of these yourself?
Open the Playground