Last active
July 28, 2020 11:21
-
-
Save rerorero/9c1b07608209d7fc3e2f to your computer and use it in GitHub Desktop.
luaj-sandbox-sampole
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import org.luaj.vm2.{LuaValue, Globals, Varargs} | |
import org.luaj.vm2.lib.jse.{JsePlatform} | |
import org.luaj.vm2.lib.{VarArgFunction} | |
import java.io.File | |
import scala.util.Try | |
class LuaArgFunction(val f: (Varargs) => Varargs) extends VarArgFunction { | |
override def invoke(args : Varargs) = f(args) | |
} | |
object LuaScalaHelper { | |
implicit def wrap(f: (Varargs) => LuaValue) : LuaArgFunction = new LuaArgFunction( args => | |
f(args) match { | |
case vars: Varargs => vars | |
case LuaValue.NONE => LuaValue.NONE | |
case ary => LuaValue.varargsOf(Array(ary)) | |
}) | |
// @todo Scala type -> Luavalue の変換 | |
} | |
trait LuaApi { | |
def load(lua : Globals) : Unit | |
} | |
// lua -> java の関数定義 | |
object LuaTicketComponent extends LuaApi { | |
import LuaScalaHelper._ | |
def load(lua : Globals): Unit = { | |
val pkg = LuaValue.tableOf() | |
// API実装 | |
pkg.set(LuaValue.valueOf("issue"), (args:Varargs) => { | |
// @todo argsのチェック | |
val name = args.tojstring(1) | |
println("ticket.issue called with " + name) | |
LuaValue.valueOf(123) | |
}) | |
// packageをluaに提供 | |
lua.set("ticket", pkg) | |
} | |
} | |
// サンドボックス | |
class LuaSandbox { | |
// @todo APIはパッケージごとにでも提供可否を変えられるといい | |
val apis = List( | |
LuaTicketComponent | |
) | |
val lua = JsePlatform.debugGlobals() | |
// @todo この辺も設定ファイルかランタイムで変更可能にする | |
lua.set("package", LuaValue.NIL) | |
lua.set("require", LuaValue.NIL) | |
lua.set("io", LuaValue.NIL) | |
lua.set("os", LuaValue.NIL) | |
//lua.set("load", LuaValue.NIL) | |
lua.set("luajava", LuaValue.NIL) | |
apis.foreach(_.load(lua)) | |
// luaj で実行 | |
def run(filepath : String) = Try { | |
// lua for JSE | |
val chunk = lua.loadfile(filepath) | |
chunk.call() | |
} | |
} | |
object main extends App { | |
val scriptPath = new File("script/sample.lua").getAbsolutePath() | |
val sandbox = new LuaSandbox | |
val res = sandbox.run(scriptPath) | |
println("==result==") | |
println(res) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment