Class AbstractLua
- All Implemented Interfaces:
AutoCloseable,Lua,LuaThread
LuaNatives for most of the features independent of Lua versions-
Nested Class Summary
Nested classes/interfaces inherited from interface party.iroiro.luajava.Lua
Lua.Conversion, Lua.LuaType -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected final LuaNativesprotected intprotected static final LuaInstances<AbstractLua>Registry of all active Lua instances.protected final longprotected @Nullable ExternalLoaderExternal loader for Lua modules.protected final AbstractLuaprotected final @Nullable ConcurrentHashMap<Integer,party.iroiro.luajava.cleaner.LuaReference<?>> Map tracking all active Lua references.protected final @Nullable ReferenceQueue<party.iroiro.luajava.cleaner.LuaReferable>Queue for tracking references that can be garbage collected.protected @Nullable LuaValueCached reference to the Lua require function.Fields inherited from interface party.iroiro.luajava.Lua
GLOBAL_THROWABLE -
Constructor Summary
ConstructorsModifierConstructorDescriptionprotectedAbstractLua(LuaNatives luaNative) Creates a new Lua (main) stateprotectedAbstractLua(LuaNatives luaNative, long L, int id, AbstractLua mainThread) Adopts a Lua sub-state, wrapping it up with the Lua interface -
Method Summary
Modifier and TypeMethodDescriptionprotected voidaddSubThread(Lua lua) Adds a sub-thread to this main thread's tracking list.protected voidcheckError(int code, boolean runtime) ThrowsLuaExceptionif the code is notLuaException.LuaError.OK.voidcheckStack(int extra) Ensures that there are at leastextrafree stack slots in the Lua stackvoidclose()Closes the threadvoidconcat(int n) Concatenates the n values at the top of the stack, pops them, and leaves the result at the topabstract LuaException.LuaErrorconvertError(int code) Converts a native error code to a LuaError enum value.abstract Lua.LuaTypeconvertType(int code) Converts a native type code to a LuaType enum value.createProxy(Class<?>[] interfaces, Lua.Conversion degree) Creates a proxy object, implementing all the specified interfaces, with a Lua table / function on top of the stackvoidcreateTable(int nArr, int nRec) Creates a new empty table and pushes it onto the stack@Nullable ByteBufferdump()Dumps a function as a binary chunkbooleanequal(int i1, int i2) Returns true if the two values in acceptable indices i1 and i2 are equalintSets the Lua globalLua.GLOBAL_THROWABLEto the throwablevoidThrows an error inside a Lua environmentLuaValue[]Executes Lua codefrom(boolean b) Creates a boolean Lua value from a Java boolean.from(double n) Creates a number Lua value from a Java double.from(long n) Creates a number Lua value from a Java long.Creates a string Lua value from a Java string.from(ByteBuffer buffer) Creates a raw string Lua value from a byte buffer.fromNull()Creates a nil Lua value.voidgc()Performs a full garbage-collection cycleget()Pops the value on top of the stack and return a LuaValue referring to itGets a references to a global objectvoidPushes onto the stack the value t[key]voidPushes onto the stack the value of the globalnameintgetId()Returns the unique identifier of this Lua thread.@Nullable ThrowableFetches the most recent JavaThrowablepassed to LuaReturns the underlying native Lua interface.Returns the main Lua state.intgetMetaField(int index, String field) Pushes onto the stack the fieldfieldfrom the metatable of the object at indexindexintgetMetatable(int index) Pushes onto the stack the metatable of the value at the given acceptable indexlongReturns the pointer to the internal Lua state.voidgetRegisteredMetatable(String typeName) Pushes onto the stack the metatable associated with name tname in the registryvoidgetTable(int index) Pushes onto the stack the value t[k]intgetTop()Returns the index of the top element in the stackvoidinsert(int index) Moves the top element into the given valid index, shifting up the elements above this indexprotected @Nullable ObjectinvokeSpecial(@Nullable Object object, Method method, @Nullable Object @Nullable [] params) Calls a method on an object, equivalent to invokespecialbooleanisBoolean(int index) Returns true if the value at the given index is a boolean, and false otherwiseprotected booleanisClosed()Checks if this Lua state has been closed.booleanisFunction(int index) Returns true if the value at the given index is a function (either C or Lua), and false otherwisebooleanisInteger(int index) Returns true if the value at the given index is an integer, and false otherwisebooleanisJavaObject(int index) Checks if the element is a Java objectbooleanisNil(int index) Returns true if the value at the given index is nil, and false otherwisebooleanisNone(int index) Returns true if the given index is not valid, and false otherwisebooleanisNoneOrNil(int index) Returns true if the given index is not valid or if the value at this index is nil, and false otherwisebooleanisNumber(int index) Returns true if the value is a number or a string convertible to a number, and false otherwisebooleanisString(int index) Returns true if the value at the given index is a string or a numberbooleanisTable(int index) Returns true if the value at the given index is a table, and false otherwise.booleanisThread(int index) Returns true if the value at the given index is a thread, and false otherwise.booleanisUserdata(int index) Returns true if the value at the given index is userdata (either full or light), and false otherwise.booleanlessThan(int i1, int i2) Returns true if the value at acceptable index i1 is smaller than the value at i2voidLoads a string as a Lua chunkvoidLoads a buffer as a Lua chunkvoidloadExternal(String module) Loads a chunk from aExternalLoaderset byLua.setExternalLoader(ExternalLoader)intnewRegisteredMetatable(String typeName) Creates a new table to be used as a metatable for userdata, adds it to the registryvoidnewTable()Creates a new empty table and pushes it onto the stackCreates a new thread, pushes it on the stackprotected abstract AbstractLuanewThread(long L, int id, AbstractLua mainThread) Creates a new sub-thread attached to this main thread.intnext(int n) Pops a key from the stack, and pushes a key-value pair from the table at the given indexvoidOpens all standard Lua libraries into the given statevoidopenLibrary(String name) Opens a specific library into the given statevoidpCall(int nArgs, int nResults) Calls a function in protected modevoidpop(int n) Pops n elements from the stackvoidpush(boolean bool) Pushes a boolean value onto the stackvoidpush(long integer) Pushes an integer onto the stackvoidpush(@Nullable Object object, Lua.Conversion degree) Push an object onto the stack, converting according toLua.Conversion.voidPushes a floating-point number onto the stackvoidPushes a string onto the stack.voidpush(ByteBuffer buffer) Pushes a buffer as a raw string onto the stackvoidpush(Collection<?> collection) Push the element onto the stack, converted to lua tables (index starting from 1)voidPush the element onto the stack, converted to lua tablesvoidPush the function onto the stack, converted to a callable elementvoidpush(LuaFunction function) Push the function onto the stack, converted to a callable elementvoidPush aLuaValueonto the stack, equivalent toLuaValue.push(Lua)voidPush an array onto the stack, converted to luatablevoidpushJavaArray(Object array) Push the element onto the stack, converted as is to Java arraysvoidpushJavaClass(Class<?> clazz) Push a class onto the stack, which may be used with `java.new` on the lua sidevoidpushJavaObject(Object object) Push the element onto the stack, converted as is to Java objectsprotected voidpushJavaObjectOrArray(Object object) Pushes a Java object or array onto the Lua stack.voidpushNil()Pushes anilvalue onto the stackvoidPushes the current thread onto the stackvoidpushValue(int index) Pushes a copy of the element at the given valid index onto the stackbooleanrawEqual(int i1, int i2) Returns true if the two values in acceptable indices i1 and i2 are primitively equalvoidrawGet(int index) Similar toLua.getTable(int), but does a raw access (i.e., without metamethods)voidrawGetI(int index, int n) Pushes onto the stack the value t[n], where t is the value at the given valid indexintrawLength(int index) Returns the raw "length" of the value at the given indexvoidrawSet(int index) Similar toLua.setTable(int), but does a raw assignment (i.e., without metamethods)voidrawSetI(int index, int n) Does the equivalent of t[n] = vintref()CallsLua.ref(int)with the pseudo-indexLUA_REGISTRYINDEXintref(int index) Creates and returns a reference, in the table at indexindexvoidrefGet(int ref) voidregister(String name, LuaFunction function) Registers the function to a global namevoidremove(int index) Removes the element at the given valid indexvoidreplace(int index) Moves the top element into the given position (and pops it)Loads a module, similar to the Lua `require` functionbooleanresume(int nArgs) Starts and resumes a coroutine in a given threadvoidLoads and runs the given stringvoidLoads and runs a buffervoidSets a global variable to the given valuevoidsetExternalLoader(ExternalLoader loader) Sets aExternalLoaderfor the main statevoidDoes the equivalent to t[key] = vvoidPops a value from the stack and sets it as the new value of globalnamevoidsetMetatable(int index) Pops a table from the stack and sets it as the new metatable for the value at the given acceptable indexvoidsetTable(int index) Does the equivalent to t[k] = vvoidsetTop(int index) Accepts any index, or 0, and sets the stack top to this indexprotected booleanA method specifically for working around deadlocks caused by LuaJ.status()Returns the status of the threadinttoAbsoluteIndex(int index) Converts a stack index into an absolute index.booleantoBoolean(int index) Converts the Lua value at the given acceptable index to a boolean value@Nullable ByteBuffertoBuffer(int index) Creates aByteBufferfrom the string at the specific index@Nullable ByteBuffertoDirectBuffer(int index) Creates a read-only directByteBufferfrom the string at the specific indexlongtoInteger(int index) Converts the Lua value at the given acceptable index to the signed integral type lua_Integer@Nullable ObjecttoJavaObject(int index) Get the element at the specified stack position, if the element is a Java object / array / class@Nullable List<?>toList(int index) Get the element at the specified stack position, converted toList@Nullable Map<?,?> toMap(int index) Get the element at the specified stack position, converted to aMapdoubletoNumber(int index) Converts the Lua value at the given acceptable index to a number@Nullable ObjecttoObject(int index) Automatically converts a value into a Java object nil is converted tonull. boolean converted tobooleanor the boxedBoolean. integer / number to any ofcharbyteshortintlongfloatdoubleor their boxed alternative. string toString. table toMap<Object, Object>, converted recursively. jclass toClass<?>. jobject to the underlying Java object. Other types are not converted and arenullon the Java side.@Nullable ObjectConverts a value at the stack index@Nullable StringtoString(int index) Converts the Lua value at the given acceptable index to a string@Nullable Lua.LuaTypetype(int index) Returns the Lua type of the element at the given index.voidunref(int ref) voidunRef(int index, int ref) Releases reference ref from the table at indexindexvoidExchange values between different threads of the same global statevoidyield(int n) Yields a coroutine
-
Field Details
-
instances
Registry of all active Lua instances. -
loader
External loader for Lua modules. -
requireFunction
Cached reference to the Lua require function. -
recyclableReferences
protected final @Nullable ReferenceQueue<party.iroiro.luajava.cleaner.LuaReferable> recyclableReferencesQueue for tracking references that can be garbage collected. -
recordedReferences
protected final @Nullable ConcurrentHashMap<Integer,party.iroiro.luajava.cleaner.LuaReference<?>> recordedReferencesMap tracking all active Lua references. -
C
-
L
protected final long L -
id
protected volatile int id -
mainThread
-
subThreads
-
-
Constructor Details
-
AbstractLua
Creates a new Lua (main) state- Parameters:
luaNative- the Lua native wrapper
-
AbstractLua
Adopts a Lua sub-state, wrapping it up with the Lua interface- Parameters:
luaNative- the Lua native wrapperL- the new Lua state pointerid- the Lua state id (seeLuaInstances)mainThread- the main state of this sub-state
-
-
Method Details
-
checkStack
Description copied from interface:LuaEnsures that there are at leastextrafree stack slots in the Lua stackIt wraps
lua_checkstack.- Specified by:
checkStackin interfaceLua- Parameters:
extra- the extra slots to ensure- Throws:
RuntimeException- when unable to grow the stack
-
push
Description copied from interface:LuaPush an object onto the stack, converting according toLua.Conversion. -
pushJavaObjectOrArray
Pushes a Java object or array onto the Lua stack.- Parameters:
object- the Java object or array to push
-
pushNil
public void pushNil()Description copied from interface:LuaPushes anilvalue onto the stack -
push
public void push(boolean bool) Description copied from interface:LuaPushes a boolean value onto the stack -
push
Description copied from interface:LuaPushes a floating-point number onto the stack- Specified by:
pushin interfaceLua- Parameters:
number- the number, whoseNumber.doubleValue()will be pushed
-
push
public void push(long integer) Description copied from interface:LuaPushes an integer onto the stackPlease note that on some 32-bit platforms, 64-bit integers are likely to get truncated instead of getting approximated into a floating-point number. If you want to approximate an integer, cast it to double and use
Lua.push(Number). -
push
Description copied from interface:LuaPushes a string onto the stack. -
push
Description copied from interface:LuaPushes a buffer as a raw string onto the stackThe pushed bytes are from buffer[buffer.position()] to buffer[buffer.limit() - 1]. So remember to call
ByteBuffer.flip()or set the position and limit before pushing. -
push
Description copied from interface:LuaPush the element onto the stack, converted to lua tablesInner elements are converted with
Lua.Conversion.FULL. -
push
Description copied from interface:LuaPush the element onto the stack, converted to lua tables (index starting from 1)Inner elements are converted with
Lua.Conversion.FULL. -
pushArray
Description copied from interface:LuaPush an array onto the stack, converted to luatable- Specified by:
pushArrayin interfaceLua- Parameters:
array- a array- Throws:
IllegalArgumentException- when the object is not array
-
push
Description copied from interface:LuaPush the function onto the stack, converted to a callable elementThe function is wrapped into a C closure, which means Lua will treat the function as a C function. Checking
Lua.isFunction(int)on the pushed element will return true. -
push
Description copied from interface:LuaPush aLuaValueonto the stack, equivalent toLuaValue.push(Lua) -
push
Description copied from interface:LuaPush the function onto the stack, converted to a callable element -
pushJavaObject
Description copied from interface:LuaPush the element onto the stack, converted as is to Java objects- Specified by:
pushJavaObjectin interfaceLua- Parameters:
object- the element to be pushed onto the stack- Throws:
IllegalArgumentException- when argument isnullor an array
-
pushJavaArray
Description copied from interface:LuaPush the element onto the stack, converted as is to Java arrays- Specified by:
pushJavaArrayin interfaceLua- Parameters:
array- the element to be pushed onto the stack- Throws:
IllegalArgumentException- when argument isnullor a non-array object
-
pushJavaClass
Description copied from interface:LuaPush a class onto the stack, which may be used with `java.new` on the lua side- Specified by:
pushJavaClassin interfaceLua- Parameters:
clazz- the class
-
toAbsoluteIndex
public int toAbsoluteIndex(int index) Converts a stack index into an absolute index.- Parameters:
index- a stack index- Returns:
- an absolute positive stack index
-
toNumber
public double toNumber(int index) Description copied from interface:LuaConverts the Lua value at the given acceptable index to a numberThe Lua value must be a number or a string convertible to a number; otherwise,
lua_tonumberreturns 0. -
toInteger
public long toInteger(int index) Description copied from interface:LuaConverts the Lua value at the given acceptable index to the signed integral type lua_IntegerThe Lua value must be a number or a string convertible to a number; otherwise,
lua_tointegerreturns 0. If the number is not an integer, it is truncated in some non-specified way. -
toBoolean
public boolean toBoolean(int index) Description copied from interface:LuaConverts the Lua value at the given acceptable index to a boolean valueLike all tests in Lua,
lua_tobooleanreturns 1 for any Lua value different fromfalseandnil; otherwise it returns 0. It also returns 0 when called with a non-valid index. -
toObject
Description copied from interface:LuaAutomatically converts a value into a Java object- nil is converted to
null. - boolean converted to
booleanor the boxedBoolean. - integer / number to any of
charbyteshortintlongfloatdoubleor their boxed alternative. - string to
String. - table to
Map<Object, Object>, converted recursively. - jclass to
Class<?>. - jobject to the underlying Java object.
- Other types are not converted and are
nullon the Java side.
- nil is converted to
-
toObject
Description copied from interface:LuaConverts a value at the stack index -
toString
Description copied from interface:LuaConverts the Lua value at the given acceptable index to a stringThe Lua value must be a string or a number; otherwise, the function returns NULL. If the value is a number, then lua_tolstring also changes the actual value in the stack to a string.
-
toBuffer
Description copied from interface:LuaCreates aByteBufferfrom the string at the specific indexYou may want to use this instead of
Lua.toString(int)when the string is binary (e.g., those returned bystring.dumpand contains null characters). -
toDirectBuffer
Description copied from interface:LuaCreates a read-only directByteBufferfrom the string at the specific indexThe memory of this buffer is managed by Lua. So you should never use the buffer after popping the corresponding value from the Lua stack.
- Specified by:
toDirectBufferin interfaceLua- Parameters:
index- the stack index- Returns:
- the created read-only buffer
-
toJavaObject
Description copied from interface:LuaGet the element at the specified stack position, if the element is a Java object / array / class- Specified by:
toJavaObjectin interfaceLua- Parameters:
index- the stack position of the element- Returns:
- the Java object or null
-
toMap
Description copied from interface:Lua -
toList
Description copied from interface:Lua -
isBoolean
public boolean isBoolean(int index) Description copied from interface:LuaReturns true if the value at the given index is a boolean, and false otherwise -
isFunction
public boolean isFunction(int index) Description copied from interface:LuaReturns true if the value at the given index is a function (either C or Lua), and false otherwiseWhen one pushes a
JFunctiononto the stack usingLua.push(JFunction), theJFunctionis wrapped into a C closure, so that it is treated as a C function in Lua.- Specified by:
isFunctionin interfaceLua- Parameters:
index- the stack index- Returns:
- true if the value at the given index is a function (either C or Lua), and false otherwise
-
isJavaObject
public boolean isJavaObject(int index) Description copied from interface:LuaChecks if the element is a Java objectNote that a
JFunctionpushed withLua.push(JFunction)is not a Java object any more, but a C function.- Specified by:
isJavaObjectin interfaceLua- Parameters:
index- the element to check type for- Returns:
trueif the element is a Java object, a Java class, or a Java array
-
isNil
public boolean isNil(int index) Description copied from interface:LuaReturns true if the value at the given index is nil, and false otherwise -
isNone
public boolean isNone(int index) Description copied from interface:LuaReturns true if the given index is not valid, and false otherwise -
isNoneOrNil
public boolean isNoneOrNil(int index) Description copied from interface:LuaReturns true if the given index is not valid or if the value at this index is nil, and false otherwise- Specified by:
isNoneOrNilin interfaceLua- Parameters:
index- the stack index- Returns:
- true if the given index is not valid or if the value at this index is nil, and false otherwise
-
isNumber
public boolean isNumber(int index) Description copied from interface:LuaReturns true if the value is a number or a string convertible to a number, and false otherwise -
isInteger
public boolean isInteger(int index) Description copied from interface:LuaReturns true if the value at the given index is an integer, and false otherwise(that is, the value is a number and is represented as an integer)
-
isString
public boolean isString(int index) Description copied from interface:LuaReturns true if the value at the given index is a string or a number -
isTable
public boolean isTable(int index) Description copied from interface:LuaReturns true if the value at the given index is a table, and false otherwise. -
isThread
public boolean isThread(int index) Description copied from interface:LuaReturns true if the value at the given index is a thread, and false otherwise. -
isUserdata
public boolean isUserdata(int index) Description copied from interface:LuaReturns true if the value at the given index is userdata (either full or light), and false otherwise.- Specified by:
isUserdatain interfaceLua- Parameters:
index- the stack index- Returns:
- true if the value at the given index is userdata (either full or light), and false otherwise.
-
type
Description copied from interface:LuaReturns the Lua type of the element at the given index. -
equal
public boolean equal(int i1, int i2) Description copied from interface:LuaReturns true if the two values in acceptable indices i1 and i2 are equalReturns true if the two values in acceptable indices index1 and index2 are equal, following the semantics of the Lua == operator (that is, may call metamethods). Otherwise returns false. Also returns false if any of the indices is non valid.
-
rawLength
public int rawLength(int index) Description copied from interface:LuaReturns the raw "length" of the value at the given indexFor strings, this is the string length; for tables, this is the result of the length operator ('#') with no metamethods; for userdata, this is the size of the block of memory allocated for the userdata. For other values, this call returns 0.
-
lessThan
public boolean lessThan(int i1, int i2) Description copied from interface:LuaReturns true if the value at acceptable index i1 is smaller than the value at i2It follows the semantics of the Lua < operator (that is, may call metamethods). Otherwise returns false. Also returns false if any of the indices is non valid.
-
rawEqual
public boolean rawEqual(int i1, int i2) Description copied from interface:LuaReturns true if the two values in acceptable indices i1 and i2 are primitively equalIt does not call metamethods. Otherwise returns false. Also returns false if any of the indices are non valid.
-
getTop
public int getTop()Description copied from interface:LuaReturns the index of the top element in the stackBecause indices start at 1, this result is equal to the number of elements in the stack (and so 0 means an empty stack).
-
setTop
public void setTop(int index) Description copied from interface:LuaAccepts any index, or 0, and sets the stack top to this indexIf the new top is greater than the old one, then the new elements are filled with nil. If index is 0, then all stack elements are removed.
-
insert
public void insert(int index) Description copied from interface:LuaMoves the top element into the given valid index, shifting up the elements above this indexMoves the top element into the given valid index, shifting up the elements above this index to open space. Cannot be called with a pseudo-index, because a pseudo-index is not an actual stack position.
-
pop
public void pop(int n) Description copied from interface:LuaPops n elements from the stack -
pushValue
public void pushValue(int index) Description copied from interface:LuaPushes a copy of the element at the given valid index onto the stack -
pushThread
public void pushThread()Description copied from interface:LuaPushes the current thread onto the stack- Specified by:
pushThreadin interfaceLua
-
remove
public void remove(int index) Description copied from interface:LuaRemoves the element at the given valid indexRemoves the element at the given valid index, shifting down the elements above this index to fill the gap. Cannot be called with a pseudo-index, because a pseudo-index is not an actual stack position.
-
replace
public void replace(int index) Description copied from interface:LuaMoves the top element into the given position (and pops it)Moves the top element into the given position (and pops it), without shifting any element (therefore replacing the value at the given position).
-
xMove
Description copied from interface:LuaExchange values between different threads of the same global stateThis function pops n values from the stack of this thread, and pushes them onto the stack of the other thread
- Specified by:
xMovein interfaceLua- Parameters:
other- the thread to move the n values ton- the number of elements to move- Throws:
IllegalArgumentException- when the two threads do not belong to the same global state
-
load
Description copied from interface:LuaLoads a string as a Lua chunkThis function eventually uses
lua_loadto load the chunk in the stringscript. Also as lua_load, this function only loads the chunk; it does not run it.- Specified by:
loadin interfaceLua- Parameters:
script- the Lua chunk- Throws:
LuaException- See Also:
-
load
Description copied from interface:LuaLoads a buffer as a Lua chunkThis function eventually uses
lua_loadto load the chunk in the stringscript. Also as lua_load, this function only loads the chunk; it does not run it.The used contents are from buffer[buffer.position()] to buffer[buffer.limit() - 1]. So remember to call
ByteBuffer.flip()or set the position and limit before pushing.- Specified by:
loadin interfaceLua- Parameters:
buffer- the buffer, must be a direct buffername- the chunk name, used for debug information and error messages- Throws:
LuaException- See Also:
-
run
Description copied from interface:LuaLoads and runs the given stringIt is equivalent to first calling
Lua.load(String)and thenLua.pCall(int, int)the loaded chunk.- Specified by:
runin interfaceLua- Parameters:
script- the Lua chunk- Throws:
LuaException
-
run
Description copied from interface:LuaLoads and runs a bufferIt is equivalent to first calling
Lua.load(Buffer, String)and thenLua.pCall(int, int)the loaded chunk.The used contents are from buffer[buffer.position()] to buffer[buffer.limit() - 1]. So remember to call
ByteBuffer.flip()or set the position and limit before pushing.- Specified by:
runin interfaceLua- Parameters:
buffer- the buffer, must be a direct buffername- the chunk name, used for debug information and error messages- Throws:
LuaException
-
dump
Description copied from interface:LuaDumps a function as a binary chunkReceives a Lua function on the top of the stack and produces a binary chunk that, if loaded again, results in a function equivalent to the one dumped.
-
pCall
Description copied from interface:LuaCalls a function in protected modeTo call a function you must use the following protocol: first, the function to be called is pushed onto the stack; then, the arguments to the function are pushed in direct order; that is, the first argument is pushed first. Finally you call lua_call; nargs is the number of arguments that you pushed onto the stack. All arguments and the function value are popped from the stack when the function is called. The function results are pushed onto the stack when the function returns. The number of results is adjusted to nresults, unless nresults is LUA_MULTRET. In this case, all results from the function are pushed. Lua takes care that the returned values fit into the stack space. The function results are pushed onto the stack in direct order (the first result is pushed first), so that after the call the last result is on the top of the stack.
- Specified by:
pCallin interfaceLua- Parameters:
nArgs- the number of arguments that you pushed onto the stacknResults- the number of results to adjust to- Throws:
LuaException
-
newThread
Description copied from interface:LuaCreates a new thread, pushes it on the stackThe new state returned by this function shares with the original state all global objects (such as tables), but has an independent execution stack.
-
addSubThread
Adds a sub-thread to this main thread's tracking list.- Parameters:
lua- the sub-thread to add
-
newThread
Creates a new sub-thread attached to this main thread.- Parameters:
L- the pointer to the new Lua stateid- the unique identifier for the new statemainThread- the main thread this state belongs to- Returns:
- the new sub-thread
-
resume
Description copied from interface:LuaStarts and resumes a coroutine in a given threadTo start a coroutine, you first create a new thread (see lua_newthread or
Lua.newThread()); then you push onto its stack the main function plus any arguments; then you call resume, with narg being the number of arguments. This call returns when the coroutine suspends or finishes its execution. When it returns, the stack contains all values passed to lua_yield, or all values returned by the body function. lua_resume returns LUA_YIELD if the coroutine yields, 0 if the coroutine finishes its execution without errors, or an error code in case of errors (see lua_pcall). In case of errors, the stack is not unwound, so you can use the debug API over it. The error message is on the top of the stack. To restart a coroutine, you put on its stack only the values to be passed as results from yield, and then call lua_resume.- Specified by:
resumein interfaceLua- Parameters:
nArgs- the number of arguments- Returns:
trueif the thread yielded, orfalseif it ended execution- Throws:
LuaException
-
status
Description copied from interface:LuaReturns the status of the thread -
yield
public void yield(int n) Description copied from interface:LuaYields a coroutineThis is not implemented because we have no way to resume execution from a Java stack through a C stack back to a Java stack.
-
newTable
public void newTable()Description copied from interface:LuaCreates a new empty table and pushes it onto the stackIt is equivalent to
createTable(0, 0). -
createTable
public void createTable(int nArr, int nRec) Description copied from interface:LuaCreates a new empty table and pushes it onto the stackThe new table has space pre-allocated for narr array elements and nrec non-array elements. This pre-allocation is useful when you know exactly how many elements the table will have.
- Specified by:
createTablein interfaceLua- Parameters:
nArr- pre-allocated array elementsnRec- pre-allocated non-array elements
-
getField
Description copied from interface:LuaPushes onto the stack the value t[key]Pushes onto the stack the value t[key], where t is the value at the given valid index. As in Lua, this function may trigger a metamethod for the "index" event.
-
setField
Description copied from interface:LuaDoes the equivalent to t[key] = vDoes the equivalent to t[key] = v, where t is the value at the given valid index and v is the value at the top of the stack. This function pops the value from the stack. As in Lua, this function may trigger a metamethod for the "newindex" event.
-
getTable
public void getTable(int index) Description copied from interface:LuaPushes onto the stack the value t[k]Pushes onto the stack the value t[k], where t is the value at the given valid index and k is the value at the top of the stack. This function pops the key from the stack (putting the resulting value in its place). As in Lua, this function may trigger a metamethod for the "index" event.
-
setTable
public void setTable(int index) Description copied from interface:LuaDoes the equivalent to t[k] = vDoes the equivalent to t[k] = v, where t is the value at the given valid index, v is the value at the top of the stack, and k is the value just below the top. This function pops both the key and the value from the stack. As in Lua, this function may trigger a metamethod for the "newindex" event.
-
next
public int next(int n) Description copied from interface:LuaPops a key from the stack, and pushes a key-value pair from the table at the given indexPops a key from the stack, and pushes a key-value pair from the table at the given index (the "next" pair after the given key). If there are no more elements in the table, then lua_next returns 0 (and pushes nothing).
A typical traversal looks like this:
/* table is in the stack at index 't' */ lua_pushnil(L); /* first key */ while (lua_next(L, t) != 0) { /* uses 'key' (at index -2) and 'value' (at index -1) */ printf("%s - %s\n", lua_typename(L, lua_type(L, -2)), lua_typename(L, lua_type(L, -1))); /* removes 'value'; keeps 'key' for next iteration */ lua_pop(L, 1); }While traversing a table, do not call
Lua.toString(int)directly on a key, unless you know that the key is actually a string. Recall thatLua.toString(int)changes the value at the given index; this confuses the next call to lua_next. -
rawGet
public void rawGet(int index) Description copied from interface:LuaSimilar toLua.getTable(int), but does a raw access (i.e., without metamethods) -
rawGetI
public void rawGetI(int index, int n) Description copied from interface:LuaPushes onto the stack the value t[n], where t is the value at the given valid indexThe access is raw; that is, it does not invoke metamethods.
-
rawSet
public void rawSet(int index) Description copied from interface:LuaSimilar toLua.setTable(int), but does a raw assignment (i.e., without metamethods) -
rawSetI
public void rawSetI(int index, int n) Description copied from interface:LuaDoes the equivalent of t[n] = vDoes the equivalent of t[n] = v, where t is the value at the given valid index and v is the value at the top of the stack.
This function pops the value from the stack. The assignment is raw; that is, it does not invoke metamethods.
-
ref
public int ref(int index) Description copied from interface:LuaCreates and returns a reference, in the table at indexindexCreates and returns a reference, in the table at index t, for the object at the top of the stack (and pops the object).
A reference is a unique integer key. As long as you do not manually add integer keys into table t, luaL_ref ensures the uniqueness of the key it returns. You can retrieve an object referred by reference r by calling
Lua.rawGetI(int, int). FunctionLua.unRef(int, int)frees a reference and its associated object. -
unRef
public void unRef(int index, int ref) Description copied from interface:LuaReleases reference ref from the table at indexindexThe entry is removed from the table, so that the referred object can be collected. The reference ref is also freed to be used again.
-
getGlobal
Description copied from interface:LuaPushes onto the stack the value of the globalname -
setGlobal
Description copied from interface:LuaPops a value from the stack and sets it as the new value of globalname -
getMetatable
public int getMetatable(int index) Description copied from interface:LuaPushes onto the stack the metatable of the value at the given acceptable indexPushes onto the stack the metatable of the value at the given acceptable index. If the index is not valid, or if the value does not have a metatable, the function returns 0 and pushes nothing on the stack.
- Specified by:
getMetatablein interfaceLua- Parameters:
index- the index of the element- Returns:
- 0 if the value does not have a metatable
-
setMetatable
public void setMetatable(int index) Description copied from interface:LuaPops a table from the stack and sets it as the new metatable for the value at the given acceptable index- Specified by:
setMetatablein interfaceLua- Parameters:
index- the index of the element
-
getMetaField
Description copied from interface:LuaPushes onto the stack the fieldfieldfrom the metatable of the object at indexindexIf the object does not have a metatable, or if the metatable does not have this field, returns 0 and pushes nothing.
- Specified by:
getMetaFieldin interfaceLua- Parameters:
index- the index of the elementfield- the meta field- Returns:
- 0 if no such field
-
getRegisteredMetatable
Description copied from interface:LuaPushes onto the stack the metatable associated with name tname in the registry- Specified by:
getRegisteredMetatablein interfaceLua- Parameters:
typeName- the name of the user-defined type- See Also:
-
newRegisteredMetatable
Description copied from interface:LuaCreates a new table to be used as a metatable for userdata, adds it to the registryIf the registry already has the key
typeName, returns 0. Otherwise, creates a new table to be used as a metatable for userdata, adds it to the registry with keytypeName, and returns 1.In both cases pushes onto the stack the final value associated with tname in the registry.
- Specified by:
newRegisteredMetatablein interfaceLua- Parameters:
typeName- the name of the user-defined type- Returns:
- 1 if added to registry, 0 if already registered
-
openLibraries
public void openLibraries()Description copied from interface:LuaOpens all standard Lua libraries into the given stateSee
Lua.openLibrary(String)for more info.- Specified by:
openLibrariesin interfaceLua
-
openLibrary
Description copied from interface:LuaOpens a specific library into the given stateSee the corresponding Lua manual for available library. For example, in Lua 5.4, calling
L.openLibrary("base")will call theluaopen_baseC function for the base library.Note that opening a library may modify global variables. For example, opening the
baselibrary in some specific Lua versions will override built-in functions likeprint. So make sure to make your modifications after opening all the libraries.- Specified by:
openLibraryin interfaceLua- Parameters:
name- the library name
-
concat
public void concat(int n) Description copied from interface:LuaConcatenates the n values at the top of the stack, pops them, and leaves the result at the topIf n is 1, the result is the single value on the stack (that is, the function does nothing); if n is 0, the result is the empty string. Concatenation is performed following the usual semantics of Lua.
-
gc
public void gc()Description copied from interface:LuaPerforms a full garbage-collection cycleThis also removes unneeded references created by finalized proxies and Lua values.
-
error
Description copied from interface:LuaThrows an error inside a Lua environmentIt currently just throws a
RuntimeException. -
createProxy
public Object createProxy(Class<?>[] interfaces, Lua.Conversion degree) throws IllegalArgumentException Description copied from interface:LuaCreates a proxy object, implementing all the specified interfaces, with a Lua table / function on top of the stackThis method pops the value on top on the stack and creates reference to it with
Lua.ref().When invoking methods, the created Java object, instead of the backing Lua table, is passed as the first parameter to the Lua function.
- Specified by:
createProxyin interfaceLua- Parameters:
interfaces- the interfaces to implementdegree- the conversion degree when passing parameters and return values- Returns:
- a proxy object, calls to which are proxied to the underlying Lua table
- Throws:
IllegalArgumentException- if not all classes are interfaces
-
register
Description copied from interface:LuaThreadRegisters the function to a global name -
setExternalLoader
Description copied from interface:LuaSets aExternalLoaderfor the main stateThe provided external loader will be integrated into Lua's module resolution progress. See require (modname) for an overview.
We will register a new searcher by appending to
package.searchers(orpackage.loadersfor Lua 5.1) to load Lua files with thisExternalLoader.You need to load the
packagelibrary to make the external loader effective.- Specified by:
setExternalLoaderin interfaceLua- Parameters:
loader- the loader that will be used to find files
-
loadExternal
Description copied from interface:LuaLoads a chunk from aExternalLoaderset byLua.setExternalLoader(ExternalLoader)- Specified by:
loadExternalin interfaceLua- Parameters:
module- the module- Throws:
LuaException
-
getLuaNatives
Description copied from interface:LuaReturns the underlying native Lua interface.- Specified by:
getLuaNativesin interfaceLua- Returns:
- the underlying
LuaNativesnatives
-
getMainState
Description copied from interface:LuaReturns the main Lua state.- Specified by:
getMainStatein interfaceLua- Returns:
- the main Lua state
-
getPointer
public long getPointer()Description copied from interface:LuaReturns the pointer to the internal Lua state.- Specified by:
getPointerin interfaceLua- Returns:
- the pointer to the internal
lua_State
-
getId
public int getId()Description copied from interface:LuaReturns the unique identifier of this Lua thread. -
getJavaError
Description copied from interface:LuaFetches the most recent JavaThrowablepassed to Lua- Specified by:
getJavaErrorin interfaceLua- Returns:
- value of the Lua global
Lua.GLOBAL_THROWABLE
-
error
Description copied from interface:LuaSets the Lua globalLua.GLOBAL_THROWABLEto the throwableIf the exception is
null, it clears the global exception and pushes nothing. Otherwise, it sets the Lua globalLua.GLOBAL_THROWABLEto the throwable, and pushesThrowable.toString()onto the stack. -
invokeSpecial
protected @Nullable Object invokeSpecial(@Nullable Object object, Method method, @Nullable Object @Nullable [] params) throws Throwable Calls a method on an object, equivalent to invokespecialInternally it uses
LuaNatives.luaJ_invokespecial(long, Class, String, String, Object, String)which then usesCallNonvirtual<Type>MethodAfunctions to avoid tons of restrictions imposed by the JVM.- Parameters:
object- thethisobjectmethod- the methodparams- the parameters- Returns:
- the return value
- Throws:
Throwable- whenever the method call throw exceptions
-
isClosed
protected boolean isClosed()Checks if this Lua state has been closed.- Returns:
- true if the state is closed, false otherwise
-
close
public void close()Description copied from interface:LuaCloses the threadYou need to make sure that you call this method no more than once, or else the Lua binary may / will very likely just crash.
- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceLua
-
ref
public int ref()Description copied from interface:LuaCallsLua.ref(int)with the pseudo-indexLUA_REGISTRYINDEX -
refGet
public void refGet(int ref) Description copied from interface:Lua -
unref
public void unref(int ref) Description copied from interface:Lua -
checkError
ThrowsLuaExceptionif the code is notLuaException.LuaError.OK.Most Lua C API functions attaches along an error message on the stack. If this method finds a string on the top of the stack, it pops the string and uses it as the exception message.
- Parameters:
code- the error code returned by Lua C APIruntime- iftrue, treat non-zero code values as runtime errors- Throws:
LuaException
-
convertError
Converts a native error code to a LuaError enum value.- Parameters:
code- the native error code- Returns:
- the corresponding LuaError value
-
convertType
Converts a native type code to a LuaType enum value.- Parameters:
code- the native type code- Returns:
- the corresponding LuaType value
-
get
Description copied from interface:LuaThreadGets a references to a global object -
set
Description copied from interface:LuaThreadSets a global variable to the given value -
eval
Description copied from interface:LuaThreadExecutes Lua code- Specified by:
evalin interfaceLuaThread- Parameters:
command- the command- Returns:
- the return values
- Throws:
LuaException
-
require
Description copied from interface:LuaThreadLoads a module, similar to the Lua `require` functionPlease note that this method will attempt to call
Lua.openLibrary("package")first and cache the globalrequirefunction.- Specified by:
requirein interfaceLuaThread- Parameters:
module- the module name- Returns:
- the module
- Throws:
LuaException
-
get
Description copied from interface:LuaPops the value on top of the stack and return a LuaValue referring to it -
fromNull
Description copied from interface:LuaThreadCreates a nil Lua value. -
from
Description copied from interface:LuaThreadCreates a boolean Lua value from a Java boolean. -
from
Description copied from interface:LuaThreadCreates a number Lua value from a Java double. -
from
Description copied from interface:LuaThreadCreates a number Lua value from a Java long. -
from
Description copied from interface:LuaThreadCreates a string Lua value from a Java string. -
from
Description copied from interface:LuaThreadCreates a raw string Lua value from a byte buffer. -
shouldSynchronize
protected boolean shouldSynchronize()A method specifically for working around deadlocks caused by LuaJ.In LuaJ bindings, without this work-around, deadlocks can happen when:
1. (Thread#A) The user synchronizes on mainThread as is required by LuaJava when used in multi-threaded environment. 2. (Thread#A) The user callsrun(String)for example, to run a Lua snippet. 3. The snippet creates a coroutine, mandating LuaJ to create a Java thread (#B). 4. Inside the coroutine (i.e., the Java thread#B), the code calls a Lua proxy object. 5. (Thread#B)LuaProxy.invoke(Object, Method, Object[])tries to synchronizes on mainThread. 6. Since thread#A is already inside a synchronization block, the two threads deadlocks.This work-around asks
LuaProxy.invoke(Object, Method, Object[])to avoid synchronization when it detects that it is called from a coroutine thread created by LuaJ.- Returns:
falseonly when invoke within a coroutine thread created by LuaJ
-