Skip to content

Instantly share code, notes, and snippets.

@mworzala
Created April 29, 2024 21:46
Show Gist options
  • Save mworzala/74f05ffba1691f3724a0bade85065f6d to your computer and use it in GitHub Desktop.
Save mworzala/74f05ffba1691f3724a0bade85065f6d to your computer and use it in GitHub Desktop.
import java.lang.foreign.*;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) throws Throwable {
try (Arena arena = Arena.ofShared()) {
SymbolLookup vmSymbols = SymbolLookup.libraryLookup(Path.of("libLuau.VM.dylib"), arena);
SymbolLookup compilerSymbols = SymbolLookup.libraryLookup(Path.of("libLuau.Compiler.dylib"), arena);
var luaL_newstate = Linker.nativeLinker().downcallHandle(
vmSymbols.find("luaL_newstate").orElseThrow(),
FunctionDescriptor.of(ValueLayout.ADDRESS)
);
var lua_close = Linker.nativeLinker().downcallHandle(
vmSymbols.find("lua_close").orElseThrow(),
FunctionDescriptor.ofVoid(ValueLayout.ADDRESS)
);
var luau_compile = Linker.nativeLinker().downcallHandle(
compilerSymbols.find("luau_compile").orElseThrow(),
FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.ADDRESS, ValueLayout.JAVA_LONG, ValueLayout.ADDRESS, ValueLayout.ADDRESS)
);
var luau_load = Linker.nativeLinker().downcallHandle(
vmSymbols.find("luau_load").orElseThrow(),
FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS, ValueLayout.ADDRESS, ValueLayout.ADDRESS, ValueLayout.JAVA_LONG, ValueLayout.JAVA_INT)
);
var luaL_openlibs = Linker.nativeLinker().downcallHandle(
vmSymbols.find("luaL_openlibs").orElseThrow(),
FunctionDescriptor.ofVoid(ValueLayout.ADDRESS)
);
var lua_pcall = Linker.nativeLinker().downcallHandle(
vmSymbols.find("lua_pcall").orElseThrow(),
FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS, ValueLayout.JAVA_INT, ValueLayout.JAVA_INT, ValueLayout.JAVA_INT)
);
MemorySegment L = (MemorySegment) luaL_newstate.invoke();
System.out.println(L);
luaL_openlibs.invokeExact(L);
var source = "print('hello from lua')";
var bytecodeSize = arena.allocate(ValueLayout.JAVA_LONG);
var sourceCStr = arena.allocateUtf8String(source);
var bytecode = (MemorySegment) luau_compile.invoke(sourceCStr, (long) source.length(), MemorySegment.NULL, bytecodeSize);
long size = bytecodeSize.get(ValueLayout.JAVA_LONG, 0);
System.out.println("size " + size);
var namecstr = arena.allocateUtf8String("main.lua");
var result = luau_load.invoke(L, namecstr, bytecode, size, 0);
System.out.println("RESULT: " + result);
//todo free bytecode
lua_pcall.invoke(L, 0, 0, 0);
lua_close.invoke(L);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment