Skip to content

Instantly share code, notes, and snippets.

@sogaiu

sogaiu/lua.clj

Last active Apr 9, 2021
Embed
What would you like to do?
calling lua from clojure
(ns liblua-clj.lua
(:require
[tech.v3.datatype.ffi :as dt-ffi]))
(set! *warn-on-reflection* true)
(def lua-def
{:luaL_newstate {:rettype :pointer
:argtypes []}
:luaL_openlibs {:rettype :void
:argtypes [['ls :pointer]]}
;; XXX: macros don't work
;; :luaL_dostring {:rettype :int16
;; :argtypes [['ls :pointer]
;; ['code :string]]}
:luaL_loadstring {:rettype :int16
:argtypes [['ls :pointer]
['code :string]]}
;; XXX: lua_pcall not found...
:lua_pcallk {:rettype :int16
:argtypes [['ls :pointer]
['nargs :int16]
['nresults :int16]
['msgh :int16]]}
:lua_close {:rettype :void
:argtypes [['ls :pointer]]}})
(defonce lua
(dt-ffi/library-singleton #'lua-def))
(dt-ffi/library-singleton-reset! lua)
(defn set-library-instance!
[lib-instance]
(dt-ffi/library-singleton-set-instance! lua lib-instance))
(defn initialize!
[]
(dt-ffi/library-singleton-set! lua "lua"))
(defn find-fn
[fn-name]
(dt-ffi/library-singleton-find-fn lua fn-name))
(dt-ffi/define-library-functions
liblua-clj.lua/lua-def find-fn nil)
(comment
(initialize!)
;; => #object[tech.v3.datatype.ffi.jna.G__7824 0x70f8d5f8 {:status :ready, :val {:lua_pcallk #object[tech.v3.datatype.ffi.jna.G__7824$invoker_lua_pcallk 0x3bdfaa63 "tech.v3.datatype.ffi.jna.G__7824$invoker_lua_pcallk@3bdfaa63"], :luaL_loadstring #object[tech.v3.datatype.ffi.jna.G__7824$invoker_luaL_loadstring 0x46d4d407 "tech.v3.datatype.ffi.jna.G__7824$invoker_luaL_loadstring@46d4d407"], :luaL_newstate #object[tech.v3.datatype.ffi.jna.G__7824$invoker_luaL_newstate 0x6baf6f4a "tech.v3.datatype.ffi.jna.G__7824$invoker_luaL_newstate@6baf6f4a"], :lua_close #object[tech.v3.datatype.ffi.jna.G__7824$invoker_lua_close 0x57156620 "tech.v3.datatype.ffi.jna.G__7824$invoker_lua_close@57156620"], :luaL_openlibs #object[tech.v3.datatype.ffi.jna.G__7824$invoker_luaL_openlibs 0x409324e6 "tech.v3.datatype.ffi.jna.G__7824$invoker_luaL_openlibs@409324e6"]}}]
(def ls
(luaL_newstate))
;; => #'liblua-clj.lua/ls
(luaL_openlibs ls)
;; => nil
(luaL_loadstring ls
(str "f = io.open(\"/tmp/lua-test.txt\", \"w\")\n"
"f:write(\"smile!\")\n"
"f:close()\n"))
;; => 0
(def LUA_MULTRET -1)
;; => #'liblua-clj.lua/LUA_MULTRET
(lua_pcallk ls 0 LUA_MULTRET 0)
;; => 0
(print (slurp "/tmp/lua-test.txt"))
;; => nil
(lua_close ls)
;; => nil
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment