Guest User

Untitled

a guest
Jan 15th, 2016
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 77.97 KB | None | 0 0
  1. /*
  2. * $Id: LuaState.java 157 2012-10-05 23:00:17Z [email protected] $
  3. * See LICENSE.txt for license terms.
  4. */
  5.  
  6. package li.cil.repack.com.naef.jnlua;
  7.  
  8. import java.io.ByteArrayInputStream;
  9. import java.io.IOException;
  10. import java.io.InputStream;
  11. import java.io.OutputStream;
  12. import java.lang.ref.PhantomReference;
  13. import java.lang.ref.ReferenceQueue;
  14. import java.lang.reflect.InvocationHandler;
  15. import java.lang.reflect.Method;
  16. import java.lang.reflect.Proxy;
  17. import java.util.HashSet;
  18. import java.util.Set;
  19.  
  20. import li.cil.repack.com.naef.jnlua.JavaReflector.Metamethod;
  21.  
  22. /**
  23. * JNLua core class representing a Lua instance.
  24. *
  25. * <p>
  26. * The class performs extensive checking on all arguments and its state.
  27. * Specifically, the following exceptions are thrown under the indicated
  28. * conditions:
  29. * </p>
  30. *
  31. * <table class="doc">
  32. * <tr>
  33. * <th>Exception</th>
  34. * <th>When</th>
  35. * </tr>
  36. * <tr>
  37. * <td>{@link java.lang.NullPointerException}</td>
  38. * <td>if an argument is <code>null</code> and the API does not explicitly
  39. * specify that the argument may be <code>null</code></td>
  40. * </tr>
  41. * <tr>
  42. * <td>{@link java.lang.IllegalStateException}</td>
  43. * <td>if the Lua state is closed and the API does not explicitly specify that
  44. * the method may be invoked on a closed Lua state</td>
  45. * </tr>
  46. * <tr>
  47. * <td>{@link java.lang.IllegalArgumentException}</td>
  48. * <td>if a stack index refers to a non-valid stack location and the API does
  49. * not explicitly specify that the stack index may be non-valid</td>
  50. * </tr>
  51. * <tr>
  52. * <td>{@link java.lang.IllegalArgumentException}</td>
  53. * <td>if a stack index refers to an stack location with value type that is
  54. * different from the value type explicitly specified in the API</td>
  55. * </tr>
  56. * <tr>
  57. * <td>{@link java.lang.IllegalArgumentException}</td>
  58. * <td>if a count is negative or out of range and the API does not explicitly
  59. * specify that the count may be negative or out of range</td>
  60. * </tr>
  61. * <tr>
  62. * <td>{@link li.cil.repack.com.naef.jnlua.LuaRuntimeException}</td>
  63. * <td>if a Lua runtime error occurs</td>
  64. * </tr>
  65. * <tr>
  66. * <td>{@link li.cil.repack.com.naef.jnlua.LuaSyntaxException}</td>
  67. * <td>if the syntax of a Lua chunk is incorrect</td>
  68. * </tr>
  69. * <tr>
  70. * <td>{@link li.cil.repack.com.naef.jnlua.LuaMemoryAllocationException}</td>
  71. * <td>if the Lua memory allocator runs out of memory or if a JNI allocation
  72. * fails</td>
  73. * </tr>
  74. * <tr>
  75. * <td>{@link li.cil.repack.com.naef.jnlua.LuaGcMetamethodException}</td>
  76. * <td>if an error occurs running a <code>__gc</code> metamethod during garbage
  77. * collection</td>
  78. * </tr>
  79. * <tr>
  80. * <td>{@link li.cil.repack.com.naef.jnlua.LuaMessageHandlerException}</td>
  81. * <td>if an error occurs running the message handler of a protected call</td>
  82. * </tr>
  83. * </table>
  84. */
  85. public class LuaState {
  86. // -- Static
  87. /**
  88. * Multiple returns pseudo return value count.
  89. */
  90. public static final int MULTRET = -1;
  91.  
  92. /**
  93. * Registry pseudo-index.
  94. */
  95. public static final int REGISTRYINDEX;
  96.  
  97. /**
  98. * OK status.
  99. *
  100. * @since JNLua 1.0.0
  101. */
  102. public static final int OK = 0;
  103.  
  104. /**
  105. * Status indicating that a thread is suspended.
  106. */
  107. public static final int YIELD = 1;
  108.  
  109. /**
  110. * Registry index of the main thread.
  111. *
  112. * @since JNLua 1.0.0
  113. */
  114. public static final int RIDX_MAINTHREAD = 1;
  115.  
  116. /**
  117. * Registry index of the global environment.
  118. *
  119. * @since JNLua 1.0.0
  120. */
  121. public static final int RIDX_GLOBALS = 2;
  122.  
  123. /**
  124. * The JNLua version. The format is &lt;major&gt;.&lt;minor&gt;.
  125. */
  126. public static final String VERSION = "1.1";
  127.  
  128. /**
  129. * The Lua version. The format is &lt;major&gt;.&lt;minor&gt;.
  130. */
  131. public static final String LUA_VERSION;
  132.  
  133. static {
  134. NativeSupport.getInstance().getLoader().load();
  135. REGISTRYINDEX = lua_registryindex();
  136. LUA_VERSION = lua_version();
  137. }
  138.  
  139. protected int REGISTRYINDEX() {
  140. return REGISTRYINDEX;
  141. }
  142.  
  143. protected String LUA_VERSION() {
  144. return LUA_VERSION;
  145. }
  146.  
  147. /**
  148. * The API version.
  149. */
  150. private static final int APIVERSION = 3;
  151.  
  152. // -- State
  153. /**
  154. * Whether the <code>lua_State</code> on the JNI side is owned by the Java
  155. * state and must be closed when the Java state closes.
  156. */
  157. private boolean ownState;
  158.  
  159. /**
  160. * The <code>lua_State</code> pointer on the JNI side. <code>0</code>
  161. * implies that this Lua state is closed. The field is modified exclusively
  162. * on the JNI side and must not be touched on the Java side.
  163. */
  164. private long luaState;
  165.  
  166. /**
  167. * The <code>lua_State</code> pointer on the JNI side for the running
  168. * coroutine. This field is modified exclusively on the JNI side and must
  169. * not be touched on the Java side.
  170. */
  171. private long luaThread;
  172.  
  173. /**
  174. * The yield flag. This field is modified from both the JNI side and Java
  175. * side and signals a pending yield.
  176. */
  177. private boolean yield;
  178.  
  179. /**
  180. * The maximum amount of memory the may be used by the Lua state, in bytes.
  181. * This can be adjusted to limit the amount of memory a state may use. If
  182. * it is reduced while a VM is active this can very quickly lead to out of
  183. * memory errors.
  184. */
  185. private int luaMemoryTotal;
  186.  
  187. /**
  188. * The amount of memory currently used by the Lua state, in bytes. This is
  189. * set from the JNI side and must not be modified from the Java side.
  190. */
  191. private int luaMemoryUsed;
  192.  
  193. /**
  194. * Ensures proper finalization of this Lua state.
  195. */
  196. private Object finalizeGuardian;
  197.  
  198. /**
  199. * The class loader for dynamically loading classes.
  200. */
  201. private ClassLoader classLoader;
  202.  
  203. /**
  204. * Reflects Java objects.
  205. */
  206. private JavaReflector javaReflector;
  207.  
  208. /**
  209. * Converts between Lua types and Java types.
  210. */
  211. private Converter converter;
  212.  
  213. /**
  214. * Set of Lua proxy phantom references for pre-mortem cleanup.
  215. */
  216. private Set<LuaValueProxyRef> proxySet = new HashSet<LuaValueProxyRef>();
  217.  
  218. /**
  219. * Reference queue for pre-mortem cleanup.
  220. */
  221. private ReferenceQueue<LuaValueProxyImpl> proxyQueue = new ReferenceQueue<LuaValueProxyImpl>();
  222.  
  223. // -- Construction
  224. /**
  225. * Creates a new instance. The class loader of this Lua state is set to the
  226. * context class loader of the calling thread. The Java reflector and the
  227. * converter are initialized with the default implementations. The Lua
  228. * state may allocate as much memory as it wants.
  229. *
  230. * @see #getClassLoader()
  231. * @see #setClassLoader(ClassLoader)
  232. * @see #getJavaReflector()
  233. * @see #setJavaReflector(JavaReflector)
  234. * @see #getConverter()
  235. * @see #setConverter(Converter)
  236. */
  237. public LuaState() {
  238. this(0L, 0);
  239. }
  240.  
  241. /**
  242. * Creates a new instance. The class loader of this Lua state is set to the
  243. * context class loader of the calling thread. The Java reflector and the
  244. * converter are initialized with the default implementations. The Lua
  245. * state may allocate only as much memory as specified. This is enforced
  246. * by a custom allocator that is only used if a maximum memory is given.
  247. *
  248. * @param memory
  249. * the maximum amount of memory this Lua state may use, in bytes
  250. * @see #getClassLoader()
  251. * @see #setClassLoader(ClassLoader)
  252. * @see #getJavaReflector()
  253. * @see #setJavaReflector(JavaReflector)
  254. * @see #getConverter()
  255. * @see #setConverter(Converter)
  256. */
  257. public LuaState(int memory) {
  258. this(0L, validateMemory(memory));
  259. }
  260.  
  261. /**
  262. * Creates a new instance.
  263. */
  264. private LuaState(long luaState, int memory) {
  265. ownState = luaState == 0L;
  266. luaMemoryTotal = memory;
  267. lua_newstate(APIVERSION, luaState);
  268. check();
  269.  
  270. // Create a finalize guardian
  271. finalizeGuardian = new Object() {
  272. @Override
  273. public void finalize() {
  274. synchronized (LuaState.this) {
  275. closeInternal();
  276. }
  277. }
  278. };
  279.  
  280. // Add metamethods
  281. for (int i = 0; i < JavaReflector.Metamethod.values().length; i++) {
  282. final JavaReflector.Metamethod metamethod = JavaReflector.Metamethod
  283. .values()[i];
  284. lua_pushjavafunction(new JavaFunction() {
  285. @Override
  286. public int invoke(LuaState luaState) {
  287. JavaFunction javaFunction = getMetamethod(
  288. luaState.toJavaObjectRaw(1), metamethod);
  289. if (javaFunction != null) {
  290. return javaFunction.invoke(LuaState.this);
  291. } else {
  292. throw new UnsupportedOperationException(
  293. metamethod.getMetamethodName());
  294. }
  295. }
  296. });
  297. lua_setfield(-2, metamethod.getMetamethodName());
  298. }
  299. lua_pop(1);
  300.  
  301. // Set fields
  302. classLoader = Thread.currentThread().getContextClassLoader();
  303. javaReflector = DefaultJavaReflector.getInstance();
  304. converter = DefaultConverter.getInstance();
  305. }
  306.  
  307. // -- Properties
  308. /**
  309. * Returns the class loader of this Lua state. The class loader is used for
  310. * dynamically loading classes.
  311. *
  312. * <p>
  313. * The method may be invoked on a closed Lua state.
  314. * </p>
  315. *
  316. * @return the class loader
  317. */
  318. public synchronized ClassLoader getClassLoader() {
  319. return classLoader;
  320. }
  321.  
  322. /**
  323. * Sets the class loader of this Lua state. The class loader is used for
  324. * dynamically loading classes.
  325. *
  326. * <p>
  327. * The method may be invoked on a closed Lua state.
  328. * </p>
  329. *
  330. * @param classLoader
  331. * the class loader to set
  332. */
  333. public synchronized void setClassLoader(ClassLoader classLoader) {
  334. if (classLoader == null) {
  335. throw new NullPointerException();
  336. }
  337. this.classLoader = classLoader;
  338. }
  339.  
  340. /**
  341. * Returns the Java reflector of this Lua state.
  342. *
  343. * <p>
  344. * The method may be invoked on a closed Lua state.
  345. * </p>
  346. *
  347. * @return the Java reflector converter
  348. */
  349. public synchronized JavaReflector getJavaReflector() {
  350. return javaReflector;
  351. }
  352.  
  353. /**
  354. * Sets the Java reflector of this Lua state.
  355. *
  356. * <p>
  357. * The method may be invoked on a closed Lua state.
  358. * </p>
  359. *
  360. * @param javaReflector
  361. * the Java reflector
  362. */
  363. public synchronized void setJavaReflector(JavaReflector javaReflector) {
  364. if (javaReflector == null) {
  365. throw new NullPointerException();
  366. }
  367. this.javaReflector = javaReflector;
  368. }
  369.  
  370. /**
  371. * Returns a metamethod for a specified object. If the object implements the
  372. * {@link li.cil.repack.com.naef.jnlua.JavaReflector} interface, the metamethod is first
  373. * queried from the object. If the object provides the requested metamethod,
  374. * that metamethod is returned. Otherwise, the method returns the metamethod
  375. * provided by the Java reflector configured in this Lua state.
  376. *
  377. * <p>
  378. * Clients requiring access to metamethods should go by this method to
  379. * ensure consistent class-by-class overriding of the Java reflector.
  380. * </p>
  381. *
  382. * @param obj
  383. * the object, or <code>null</code>
  384. * @return the Java reflector
  385. */
  386. public synchronized JavaFunction getMetamethod(Object obj,
  387. Metamethod metamethod) {
  388. if (obj != null && obj instanceof JavaReflector) {
  389. JavaFunction javaFunction = ((JavaReflector) obj)
  390. .getMetamethod(metamethod);
  391. if (javaFunction != null) {
  392. return javaFunction;
  393. }
  394. }
  395. return javaReflector.getMetamethod(metamethod);
  396. }
  397.  
  398. /**
  399. * Returns the converter of this Lua state.
  400. *
  401. * <p>
  402. * The method may be invoked on a closed Lua state.
  403. * </p>
  404. *
  405. * @return the converter
  406. */
  407. public synchronized Converter getConverter() {
  408. return converter;
  409. }
  410.  
  411. /**
  412. * Sets the converter of this Lua state.
  413. *
  414. * <p>
  415. * The method may be invoked on a closed Lua state.
  416. * </p>
  417. *
  418. * @param converter
  419. * the converter
  420. */
  421. public synchronized void setConverter(Converter converter) {
  422. if (converter == null) {
  423. throw new NullPointerException();
  424. }
  425. this.converter = converter;
  426. }
  427.  
  428. // -- Memory
  429. /**
  430. * Returns the maximum memory consumption of this Lua state. This is the
  431. * maximum raw memory Lua may allocate for this state, in bytes.
  432. *
  433. * @return the maximum memory consumption
  434. */
  435. public synchronized int getTotalMemory() {
  436. return luaMemoryTotal;
  437. }
  438.  
  439. /**
  440. * Sets the maximum amount of memory this Lua state may allocate. This is
  441. * the size of the raw memory the Lua library may allocate for this tate,
  442. * in bytes. Note that you can only set the maximum memory consumption for
  443. * states that were created to enforce a maximum memory consumption.
  444. *
  445. * @param value
  446. * the new maximum memory size this state may allocate
  447. */
  448. public synchronized void setTotalMemory(int value) {
  449. if (luaMemoryTotal < 1) {
  450. throw new IllegalStateException("cannot set maximum memory for this state");
  451. }
  452. luaMemoryTotal = validateMemory(value);
  453. }
  454.  
  455. /**
  456. * Returns the current amount of unused memory by this Lua state. This is
  457. * the size of the total available memory minus the raw memory currently
  458. * allocated by this state, in bytes.
  459. *
  460. * This is guaranteed to be less or equal to {@link #getTotalMemory()} and
  461. * larger or equal to zero.
  462. *
  463. * This only returns something not zero if a maximum memory consumption is
  464. * enforced by this state. Otherwise it will always return zero.
  465. *
  466. * @return the current memory consumption
  467. */
  468. public synchronized int getFreeMemory() {
  469. // This is the reason we use free amount instead of used amount: if we
  470. // lower the max memory we can get below used memory, which would be
  471. // weird; so we just say free memory is zero, which is more intuitive
  472. // and true at the same time.
  473. return Math.max(0, luaMemoryTotal - luaMemoryUsed);
  474. }
  475.  
  476. /**
  477. * Returns the approximate memory usage of the Lua coroutine on the
  478. * Lua stack
  479. *
  480. * @return the approximate coroutine memory usage
  481. */
  482. public synchronized int getCoroutineMemory() {
  483. return lua_getcoroutinemem();
  484. }
  485.  
  486. // -- Life cycle
  487. /**
  488. * Returns whether this Lua state is open.
  489. *
  490. * <p>
  491. * The method may be invoked on a closed Lua state.
  492. * </p>
  493. *
  494. * @return whether this Lua state is open
  495. */
  496. public final synchronized boolean isOpen() {
  497. return isOpenInternal();
  498. }
  499.  
  500. /**
  501. * Closes this Lua state and releases all resources.
  502. *
  503. * <p>
  504. * The method may be invoked on a closed Lua state and has no effect in that
  505. * case.
  506. * </p>
  507. */
  508. public synchronized void close() {
  509. closeInternal();
  510. }
  511.  
  512. /**
  513. * Performs a garbage collection operation. Please see the Lua Reference
  514. * Manual for an explanation of the actions, arguments and return values.
  515. *
  516. * @param what
  517. * the operation to perform
  518. * @param data
  519. * the argument required by some operations
  520. * @return a return value depending on the GC operation performed
  521. */
  522. public synchronized int gc(GcAction what, int data) {
  523. check();
  524. return lua_gc(what.ordinal(), data);
  525. }
  526.  
  527. // -- Registration
  528. /**
  529. * Opens the specified library in this Lua state. The library is pushed onto
  530. * the stack.
  531. *
  532. * @param library
  533. * the library
  534. */
  535. public synchronized void openLib(Library library) {
  536. check();
  537. library.open(this);
  538. }
  539.  
  540. /**
  541. * Opens the Lua standard libraries and the JNLua Java module in this Lua
  542. * state.
  543. *
  544. * <p>
  545. * The method opens all libraries defined by the {@link Library}
  546. * enumeration.
  547. * </p>
  548. */
  549. public synchronized void openLibs() {
  550. check();
  551. for (Library library : Library.values()) {
  552. library.open(this);
  553. pop(1);
  554. }
  555. }
  556.  
  557. /**
  558. * Registers a named Java function as a global variable.
  559. *
  560. * @param namedJavaFunction
  561. * the Java function to register
  562. */
  563. public synchronized void register(NamedJavaFunction namedJavaFunction) {
  564. check();
  565. String name = namedJavaFunction.getName();
  566. if (name == null) {
  567. throw new IllegalArgumentException("anonymous function");
  568. }
  569. pushJavaFunction(namedJavaFunction);
  570. setGlobal(name);
  571. }
  572.  
  573. /**
  574. * Registers a module and pushes the module on the stack. Optionally, a
  575. * module can be registered globally. As of Lua 5.2, modules are <i>not</i>
  576. * expected to set global variables anymore.
  577. *
  578. * @param moduleName
  579. * the module name
  580. * @param namedJavaFunctions
  581. * the Java functions of the module
  582. * @param global
  583. * whether to register the module globally
  584. */
  585. public synchronized void register(String moduleName,
  586. NamedJavaFunction[] namedJavaFunctions, boolean global) {
  587. check();
  588. /*
  589. * The following code corresponds to luaL_requiref() and must be kept in
  590. * sync. The original code cannot be called due to the necessity of
  591. * pushing each C function with an individual closure.
  592. */
  593. newTable(0, namedJavaFunctions.length);
  594. for (int i = 0; i < namedJavaFunctions.length; i++) {
  595. String name = namedJavaFunctions[i].getName();
  596. if (name == null) {
  597. throw new IllegalArgumentException(String.format(
  598. "anonymous function at index %d", i));
  599. }
  600. pushJavaFunction(namedJavaFunctions[i]);
  601. setField(-2, name);
  602. }
  603. lua_getsubtable(REGISTRYINDEX(), "_LOADED");
  604. pushValue(-2);
  605. setField(-2, moduleName);
  606. pop(1);
  607. if (global) {
  608. rawGet(REGISTRYINDEX(), RIDX_GLOBALS);
  609. pushValue(-2);
  610. setField(-2, moduleName);
  611. pop(1);
  612. }
  613. }
  614.  
  615. // -- Load and dump
  616. /**
  617. * Loads a Lua chunk from an input stream and pushes it on the stack as a
  618. * function. Depending on the value of mode, the the Lua chunk can either be
  619. * a pre-compiled binary chunk or a UTF-8 encoded text chunk.
  620. *
  621. * @param inputStream
  622. * the input stream
  623. * @param chunkName
  624. * the name of the chunk for use in error messages
  625. * @param mode
  626. * <code>"b"</code> to accept binary, <code>"t"</code> to accept
  627. * text, or <code>"bt"</code> to accept both
  628. * @throws IOException
  629. * if an IO error occurs
  630. */
  631. public synchronized void load(InputStream inputStream, String chunkName,
  632. String mode) throws IOException {
  633. check();
  634. lua_load(inputStream, chunkName, mode);
  635. }
  636.  
  637. /**
  638. * Loads a Lua chunk from a string and pushes it on the stack as a function.
  639. * The string must contain a source chunk.
  640. *
  641. * @param chunk
  642. * the Lua source chunk
  643. * @param chunkName
  644. * the name of the chunk for use in error messages
  645. */
  646. public synchronized void load(String chunk, String chunkName) {
  647. check();
  648. try {
  649. load(new ByteArrayInputStream(chunk.getBytes("UTF-8")), chunkName,
  650. "t");
  651. } catch (IOException e) {
  652. throw new LuaMemoryAllocationException(e.getMessage(), e);
  653. }
  654. }
  655.  
  656. /**
  657. * Dumps the function on top of the stack as a pre-compiled binary chunk
  658. * into an output stream.
  659. *
  660. * @param outputStream
  661. * the output stream
  662. * @throws IOException
  663. * if an IO error occurs
  664. */
  665. public synchronized void dump(OutputStream outputStream) throws IOException {
  666. check();
  667. lua_dump(outputStream);
  668. }
  669.  
  670. // -- Call
  671. /**
  672. * Calls a Lua function. The function to call and the specified number of
  673. * arguments are on the stack. After the call, the specified number of
  674. * returns values are on stack. If the number of return values has been
  675. * specified as {@link #MULTRET}, the number of values on the stack
  676. * corresponds the to number of values actually returned by the called
  677. * function.
  678. *
  679. * @param argCount
  680. * the number of arguments
  681. * @param returnCount
  682. * the number of return values, or {@link #MULTRET} to accept all
  683. * values returned by the function
  684. */
  685. public synchronized void call(int argCount, int returnCount) {
  686. check();
  687. lua_pcall(argCount, returnCount);
  688. }
  689.  
  690. // -- Globals
  691. /**
  692. * Pushes the value of a global variable on the stack.
  693. *
  694. * @param name
  695. * the global variable name
  696. */
  697. public synchronized void getGlobal(String name) {
  698. check();
  699. lua_getglobal(name);
  700. }
  701.  
  702. /**
  703. * Sets the value on top of the stack as a global variable and pops the
  704. * value from the stack.
  705. *
  706. * @param name
  707. * the global variable name
  708. */
  709. public synchronized void setGlobal(String name)
  710. throws LuaMemoryAllocationException, LuaRuntimeException {
  711. check();
  712. lua_setglobal(name);
  713. }
  714.  
  715. // -- Stack push
  716. /**
  717. * Pushes a boolean value on the stack.
  718. *
  719. * @param b
  720. * the boolean value to push
  721. */
  722. public synchronized void pushBoolean(boolean b) {
  723. check();
  724. lua_pushboolean(b ? 1 : 0);
  725. }
  726.  
  727. /**
  728. * Pushes a byte array value as a string value on the stack.
  729. *
  730. * @param b
  731. * the byte array to push
  732. */
  733. public synchronized void pushByteArray(byte[] b) {
  734. check();
  735. lua_pushbytearray(b);
  736. }
  737.  
  738. /**
  739. * Pushes an integer value as a number value on the stack.
  740. *
  741. * @param n
  742. * the integer value to push
  743. */
  744. public synchronized void pushInteger(int n) {
  745. check();
  746. lua_pushinteger(n);
  747. }
  748.  
  749. /**
  750. * Pushes a Java function on the stack.
  751. *
  752. * @param javaFunction
  753. * the function to push
  754. */
  755. public synchronized void pushJavaFunction(JavaFunction javaFunction) {
  756. check();
  757. lua_pushjavafunction(javaFunction);
  758. }
  759.  
  760. /**
  761. * Pushes a Java object on the stack with conversion. The object is
  762. * processed the by the configured converter.
  763. *
  764. * @param object
  765. * the Java object
  766. * @see #getConverter()
  767. * @see #setConverter(Converter)
  768. */
  769. public synchronized void pushJavaObject(Object object) {
  770. check();
  771. getConverter().convertJavaObject(this, object);
  772. }
  773.  
  774. /**
  775. * Pushes a Java object on the stack. The object is pushed "as is", i.e.
  776. * without conversion.
  777. *
  778. * <p>
  779. * If you require to push a Lua value that represents the Java object, then
  780. * invoke <code>pushJavaObject(object)</code>.
  781. * </p>
  782. *
  783. * <p>
  784. * You cannot push <code>null</code> without conversion since
  785. * <code>null</code> is not a Java object. The converter converts
  786. * <code>null</code> to <code>nil</code>.
  787. * </p>
  788. *
  789. * @param object
  790. * the Java object
  791. * @see #pushJavaObject(Object)
  792. */
  793. public synchronized void pushJavaObjectRaw(Object object) {
  794. check();
  795. lua_pushjavaobject(object);
  796. }
  797.  
  798. /**
  799. * Pushes a nil value on the stack.
  800. */
  801. public synchronized void pushNil() {
  802. check();
  803. lua_pushnil();
  804. }
  805.  
  806. /**
  807. * Pushes a number value on the stack.
  808. *
  809. * @param n
  810. * the number to push
  811. */
  812. public synchronized void pushNumber(double n) {
  813. check();
  814. lua_pushnumber(n);
  815. }
  816.  
  817. /**
  818. * Pushes a string value on the stack.
  819. *
  820. * @param s
  821. * the string value to push
  822. */
  823. public synchronized void pushString(String s) {
  824. check();
  825. lua_pushstring(s);
  826. }
  827.  
  828. // -- Stack type test
  829. /**
  830. * Returns whether the value at the specified stack index is a boolean.
  831. *
  832. * <p>
  833. * The stack index may be non-valid.
  834. * </p>
  835. *
  836. * @param index
  837. * the stack index
  838. * @return whether the value is a boolean
  839. */
  840. public synchronized boolean isBoolean(int index) {
  841. check();
  842. return lua_isboolean(index) != 0;
  843. }
  844.  
  845. /**
  846. * Returns whether the value at the specified stack index is a C function.
  847. *
  848. * <p>
  849. * The stack index may be non-valid.
  850. * </p>
  851. *
  852. * @param index
  853. * the stack index
  854. * @return whether the value is a function
  855. */
  856. public synchronized boolean isCFunction(int index) {
  857. check();
  858. return lua_iscfunction(index) != 0;
  859. }
  860.  
  861. /**
  862. * Returns whether the value at the specified stack index is a function
  863. * (either a C function, a Java function or a Lua function.)
  864. *
  865. * <p>
  866. * The stack index may be non-valid.
  867. * </p>
  868. *
  869. * @param index
  870. * the stack index
  871. * @return whether the value is a function
  872. */
  873. public synchronized boolean isFunction(int index) {
  874. check();
  875. return lua_isfunction(index) != 0;
  876. }
  877.  
  878. /**
  879. * Returns whether the value at the specified stack index is a Java
  880. * function.
  881. *
  882. * <p>
  883. * The stack index may be non-valid.
  884. * </p>
  885. *
  886. * @param index
  887. * the stack index
  888. * @return whether the value is a function
  889. */
  890. public synchronized boolean isJavaFunction(int index) {
  891. check();
  892. return lua_isjavafunction(index) != 0;
  893. }
  894.  
  895. /**
  896. * Returns whether the value at the specified stack index is convertible to
  897. * a Java object of the specified type. The conversion is checked by the
  898. * configured converter.
  899. *
  900. * <p>
  901. * The stack index may be non-valid.
  902. * </p>
  903. *
  904. * @param index
  905. * the stack index
  906. * @return whether the value is convertible to a Java object of the
  907. * specified type
  908. * @see #setConverter(Converter)
  909. * @see #getConverter()
  910. */
  911. public synchronized boolean isJavaObject(int index, Class<?> type) {
  912. check();
  913. return converter.getTypeDistance(this, index, type) != Integer.MAX_VALUE;
  914. }
  915.  
  916. /**
  917. * Returns whether the value at the specified stack index is a Java object.
  918. *
  919. * <p>
  920. * Note that the method does not perform conversion. If you want to check if
  921. * a value <i>is convertible to</i> a Java object, then invoke <code>
  922. * isJavaObject(index, Object.class)</code>.
  923. * </p>
  924. *
  925. * <p>
  926. * The stack index may be non-valid.
  927. * </p>
  928. *
  929. * @param index
  930. * the stack index
  931. * @return whether the value is a Java object
  932. * @see #isJavaObject(int, Class)
  933. */
  934. public synchronized boolean isJavaObjectRaw(int index) {
  935. check();
  936. return lua_isjavaobject(index) != 0;
  937. }
  938.  
  939. /**
  940. * Returns whether the value at the specified stack index is
  941. * <code>nil</code>.
  942. *
  943. * <p>
  944. * The stack index may be non-valid.
  945. * </p>
  946. *
  947. * @param index
  948. * the stack index
  949. * @return whether the value is <code>nil</code>
  950. */
  951. public synchronized boolean isNil(int index) {
  952. check();
  953. return lua_isnil(index) != 0;
  954. }
  955.  
  956. /**
  957. * Returns whether the specified stack index is non-valid.
  958. *
  959. * <p>
  960. * The stack index may be non-valid.
  961. * </p>
  962. *
  963. * @param index
  964. * the stack index
  965. * @return whether the stack index is non-valid
  966. */
  967. public synchronized boolean isNone(int index) {
  968. check();
  969. return lua_isnone(index) != 0;
  970. }
  971.  
  972. /**
  973. * Returns whether the specified stack index is non-valid or its value is
  974. * <code>nil</code>.
  975. *
  976. * <p>
  977. * The stack index may be non-valid.
  978. * </p>
  979. *
  980. * @param index
  981. * the stack index
  982. * @return whether the stack index is non-valid or its value is
  983. * <code>nil</code>
  984. */
  985. public synchronized boolean isNoneOrNil(int index) {
  986. check();
  987. return lua_isnoneornil(index) != 0;
  988. }
  989.  
  990. /**
  991. * Returns whether the value at the specified stack index is a number or a
  992. * string convertible to a number.
  993. *
  994. * <p>
  995. * The stack index may be non-valid.
  996. * </p>
  997. *
  998. * @param index
  999. * the stack index
  1000. * @return whether the value is a number or a string convertible to a number
  1001. */
  1002. public synchronized boolean isNumber(int index) {
  1003. check();
  1004. return lua_isnumber(index) != 0;
  1005. }
  1006.  
  1007. /**
  1008. * Returns whether the value at the specified stack index is a string or a
  1009. * number (which is always convertible to a string.)
  1010. *
  1011. * <p>
  1012. * The stack index may be non-valid.
  1013. * </p>
  1014. *
  1015. * @param index
  1016. * the stack index
  1017. * @return whether the value is a string or a number
  1018. */
  1019. public synchronized boolean isString(int index) {
  1020. check();
  1021. return lua_isstring(index) != 0;
  1022. }
  1023.  
  1024. /**
  1025. * Returns whether the value at the specified stack index is a table.
  1026. *
  1027. * <p>
  1028. * The stack index may be non-valid.
  1029. * </p>
  1030. *
  1031. * @param index
  1032. * the stack index
  1033. * @return whether the value is a table
  1034. */
  1035. public synchronized boolean isTable(int index) {
  1036. check();
  1037. return lua_istable(index) != 0;
  1038. }
  1039.  
  1040. /**
  1041. * Returns whether the value at the specified stack index is a thread.
  1042. *
  1043. * <p>
  1044. * The stack index may be non-valid.
  1045. * </p>
  1046. *
  1047. * @param index
  1048. * the stack index
  1049. * @return whether the value is a thread
  1050. */
  1051. public synchronized boolean isThread(int index) {
  1052. check();
  1053. return lua_isthread(index) != 0;
  1054. }
  1055.  
  1056. // -- Stack query
  1057. /**
  1058. * Compares the values at two specified stack indexes for the specified
  1059. * operator according to Lua semantics.
  1060. *
  1061. * <p>
  1062. * Any stack index may be non-valid in which case the method returns
  1063. * <code>false</code>.
  1064. * </p>
  1065. *
  1066. * @param index1
  1067. * the first stack index
  1068. * @param index2
  1069. * the second stack index
  1070. * @param operator
  1071. * the operator
  1072. * @return the result of the comparison
  1073. * @since JNLua 1.0.0
  1074. */
  1075. public synchronized boolean compare(int index1, int index2,
  1076. RelOperator operator) {
  1077. check();
  1078. return lua_compare(index1, index2, operator.ordinal()) != 0;
  1079. }
  1080.  
  1081. /**
  1082. * Returns whether the values at two specified stack indexes are equal
  1083. * according to Lua semantics.
  1084. *
  1085. * @param index1
  1086. * the first stack index
  1087. * @param index2
  1088. * the second stack index
  1089. * @return whether the values are equal
  1090. * @deprecated instead use {@link #compare(int, int, RelOperator)}
  1091. */
  1092. public synchronized boolean equal(int index1, int index2) {
  1093. return compare(index1, index2, RelOperator.EQ);
  1094. }
  1095.  
  1096. /**
  1097. * Returns the length of the value at the specified stack index. Please see
  1098. * the Lua Reference Manual for the definition of the raw length of a value.
  1099. *
  1100. * @param index
  1101. * the stack index
  1102. * @return the length
  1103. * @deprecated instead use {@link #rawLen(int)}
  1104. */
  1105. public synchronized int length(int index) {
  1106. return rawLen(index);
  1107. }
  1108.  
  1109. /**
  1110. * Returns whether a value at a first stack index is less than the value at
  1111. * a second stack index according to Lua semantics.
  1112. *
  1113. * @param index1
  1114. * the first stack index
  1115. * @param index2
  1116. * the second stack index
  1117. * @return whether the value at the first index is less than the value at
  1118. * the second index
  1119. * @deprecated instead use {@link #compare(int, int, RelOperator)}
  1120. */
  1121. public synchronized boolean lessThan(int index1, int index2)
  1122. throws LuaMemoryAllocationException, LuaRuntimeException {
  1123. return compare(index1, index2, RelOperator.LT);
  1124. }
  1125.  
  1126. /**
  1127. * Bypassing metatable logic, returns whether the values at two specified
  1128. * stack indexes are equal according to Lua semantics.
  1129. *
  1130. * <p>
  1131. * Any stack index may be non-valid in which case the method returns
  1132. * <code>false</code>.
  1133. * </p>
  1134. *
  1135. * @param index1
  1136. * the first stack index
  1137. * @param index2
  1138. * the second stack index
  1139. * @return whether the values are equal
  1140. */
  1141. public synchronized boolean rawEqual(int index1, int index2) {
  1142. check();
  1143. return lua_rawequal(index1, index2) != 0;
  1144. }
  1145.  
  1146. /**
  1147. * Bypassing metatable logic, returns the length of the value at the
  1148. * specified stack index. Please see the Lua Reference Manual for the
  1149. * definition of the raw length of a value.
  1150. *
  1151. * @param index
  1152. * the stack index
  1153. * @return the length
  1154. * @since JNLua 1.0.0
  1155. */
  1156. public synchronized int rawLen(int index) {
  1157. check();
  1158. return lua_rawlen(index);
  1159. }
  1160.  
  1161. /**
  1162. * Returns the boolean representation of the value at the specified stack
  1163. * index. The boolean representation is <code>true</code> for all values
  1164. * except <code>false</code> and <code>nil</code>. The method also returns
  1165. * <code>false</code> if the index is non-valid.
  1166. *
  1167. * @param index
  1168. * the stack index
  1169. * @return the boolean representation of the value
  1170. */
  1171. public synchronized boolean toBoolean(int index) {
  1172. check();
  1173. return lua_toboolean(index) != 0;
  1174. }
  1175.  
  1176. /**
  1177. * Returns the byte array representation of the value at the specified stack
  1178. * index. The value must be a string or a number. If the value is a number,
  1179. * it is in place converted to a string. Otherwise, the method returns
  1180. * <code>null</code>.
  1181. *
  1182. * @param index
  1183. * the stack index
  1184. * @return the byte array representation of the value
  1185. */
  1186. public synchronized byte[] toByteArray(int index) {
  1187. check();
  1188. return lua_tobytearray(index);
  1189. }
  1190.  
  1191. /**
  1192. * Returns the integer representation of the value at the specified stack
  1193. * index. The value must be a number or a string convertible to a number.
  1194. * Otherwise, the method returns <code>0</code>.
  1195. *
  1196. * @param index
  1197. * the stack index
  1198. * @return the integer representation, or <code>0</code>
  1199. */
  1200. public synchronized int toInteger(int index) {
  1201. check();
  1202. return lua_tointeger(index);
  1203. }
  1204.  
  1205. /**
  1206. * Returns the integer representation of the value at the specified stack
  1207. * index. The value must be a number or a string convertible to a number.
  1208. * Otherwise, the method returns <code>null</code>.
  1209. *
  1210. * @param index
  1211. * the stack index
  1212. * @return the integer representation, or <code>null</code>
  1213. * @since JNLua 1.0.2
  1214. */
  1215. public synchronized Integer toIntegerX(int index) {
  1216. check();
  1217. return lua_tointegerx(index);
  1218. }
  1219.  
  1220. /**
  1221. * Returns the Java function of the value at the specified stack index. If
  1222. * the value is not a Java function, the method returns <code>null</code>.
  1223. *
  1224. * @param index
  1225. * the stack index
  1226. * @return the Java function, or <code>null</code>
  1227. */
  1228. public synchronized JavaFunction toJavaFunction(int index) {
  1229. check();
  1230. return lua_tojavafunction(index);
  1231. }
  1232.  
  1233. /**
  1234. * Returns a Java object of the specified type representing the value at the
  1235. * specified stack index. The value must be convertible to a Java object of
  1236. * the specified type. The conversion is executed by the configured
  1237. * converter.
  1238. *
  1239. * @param index
  1240. * the stack index
  1241. * @param type
  1242. * the Java type to convert to
  1243. * @return the object
  1244. * @throws ClassCastException
  1245. * if the conversion is not supported by the converter
  1246. * @see #getConverter()
  1247. * @see #setConverter(Converter)
  1248. */
  1249. public synchronized <T> T toJavaObject(int index, Class<T> type) {
  1250. check();
  1251. return converter.convertLuaValue(this, index, type);
  1252. }
  1253.  
  1254. /**
  1255. * Returns the Java object of the value at the specified stack index. If the
  1256. * value is not a Java object, the method returns <code>null</code>.
  1257. *
  1258. * <p>
  1259. * Note that the method does not convert values to Java objects. If you
  1260. * require <i>any</i> Java object that represents the value at the specified
  1261. * index, then invoke <code>toJavaObject(index, Object.class)</code>.
  1262. * </p>
  1263. *
  1264. * @param index
  1265. * the stack index
  1266. * @return the Java object, or <code>null</code>
  1267. * @see #toJavaObject(int, Class)
  1268. */
  1269. public synchronized Object toJavaObjectRaw(int index) {
  1270. check();
  1271. return lua_tojavaobject(index);
  1272. }
  1273.  
  1274. /**
  1275. * Returns the number representation of the value at the specified stack
  1276. * index. The value must be a number or a string convertible to a number.
  1277. * Otherwise, the method returns <code>0.0</code>.
  1278. *
  1279. * @param index
  1280. * the stack index
  1281. * @return the number representation, or <code>0.0</code>
  1282. */
  1283. public synchronized double toNumber(int index) {
  1284. check();
  1285. return lua_tonumber(index);
  1286. }
  1287.  
  1288. /**
  1289. * Returns the number representation of the value at the specified stack
  1290. * index. The value must be a number or a string convertible to a number.
  1291. * Otherwise, the method returns <code>null</code>.
  1292. *
  1293. * @param index
  1294. * the stack index
  1295. * @return the number representation, or <code>null</code>
  1296. * @since JNLua 1.0.2
  1297. */
  1298. public synchronized Double toNumberX(int index) {
  1299. check();
  1300. return lua_tonumberx(index);
  1301. }
  1302.  
  1303. /**
  1304. * Returns the pointer representation of the value at the specified stack
  1305. * index. The value must be a table, thread, function or userdata (such as a
  1306. * Java object.) Otherwise, the method returns <code>0L</code>. Different
  1307. * values return different pointers. Other than that, the returned value has
  1308. * no portable significance.
  1309. *
  1310. * @param index
  1311. * the stack index
  1312. * @return the pointer representation, or <code>0L</code> if none
  1313. */
  1314. public synchronized long toPointer(int index) {
  1315. check();
  1316. return lua_topointer(index);
  1317. }
  1318.  
  1319. /**
  1320. * Returns the string representation of the value at the specified stack
  1321. * index. The value must be a string or a number. If the value is a number,
  1322. * it is in place converted to a string. Otherwise, the method returns
  1323. * <code>null</code>.
  1324. *
  1325. * @param index
  1326. * the stack index
  1327. * @return the string representation, or <code>null</code>
  1328. */
  1329. public synchronized String toString(int index) {
  1330. check();
  1331. return lua_tostring(index);
  1332. }
  1333.  
  1334. /**
  1335. * Returns the type of the value at the specified stack index.
  1336. *
  1337. * <p>
  1338. * The stack index may be non-valid.
  1339. * </p>
  1340. *
  1341. * @param index
  1342. * the stack index
  1343. * @return the type, or <code>null</code> if the stack index is non-valid
  1344. */
  1345. public synchronized LuaType type(int index) {
  1346. check();
  1347. int type = lua_type(index);
  1348. return type >= 0 ? LuaType.values()[type] : null;
  1349. }
  1350.  
  1351. /**
  1352. * Returns the name of the type at the specified stack index. The type name
  1353. * is the display text for the Lua type except for Java objects where the
  1354. * type name is the canonical class name.
  1355. *
  1356. * <p>
  1357. * The stack index may be non-valid in which case the method returns the
  1358. * string <code>"none"</code>.
  1359. * </p>
  1360. *
  1361. * @param index
  1362. * the index
  1363. * @return the type name
  1364. * @see LuaType#displayText()
  1365. * @see Class#getCanonicalName()
  1366. */
  1367. public synchronized String typeName(int index) {
  1368. check();
  1369. LuaType type = type(index);
  1370. if (type == null) {
  1371. return "none";
  1372. }
  1373. switch (type) {
  1374. case USERDATA:
  1375. if (isJavaObjectRaw(index)) {
  1376. Object object = toJavaObjectRaw(index);
  1377. Class<?> clazz;
  1378. if (object instanceof Class<?>) {
  1379. clazz = (Class<?>) object;
  1380. } else {
  1381. clazz = object.getClass();
  1382. }
  1383. return clazz.getCanonicalName();
  1384. }
  1385. break;
  1386. }
  1387. return type.displayText();
  1388. }
  1389.  
  1390. // -- Stack operation
  1391. /**
  1392. * Returns the absolute stack index of the specified index.
  1393. *
  1394. * <p>
  1395. * The stack index may be non-valid.
  1396. * </p>
  1397. *
  1398. * @param index
  1399. * the stack index
  1400. * @return the absolute stack index
  1401. * @since JNLua 1.0.0
  1402. */
  1403. public synchronized int absIndex(int index) {
  1404. check();
  1405. return lua_absindex(index);
  1406. }
  1407.  
  1408. /**
  1409. * Performs an arithmetic operation with values on top of the stack using
  1410. * Lua semantics.
  1411. *
  1412. * @param operator
  1413. * the operator to apply
  1414. * @since JNLua 1.0.0
  1415. */
  1416. public synchronized void arith(ArithOperator operator) {
  1417. check();
  1418. lua_arith(operator.ordinal());
  1419. }
  1420.  
  1421. /**
  1422. * Concatenates the specified number values on top of the stack and replaces
  1423. * them with the concatenated value.
  1424. *
  1425. * @param n
  1426. * the number of values to concatenate
  1427. */
  1428. public synchronized void concat(int n) {
  1429. check();
  1430. lua_concat(n);
  1431. }
  1432.  
  1433. /**
  1434. * Copies a value at a specified index to another index, replacing the value
  1435. * at that index.
  1436. *
  1437. * @param fromIndex
  1438. * the index to copy from
  1439. * @param toIndex
  1440. * the index to copy to
  1441. * @since JNLua 1.0.0
  1442. */
  1443. public synchronized void copy(int fromIndex, int toIndex) {
  1444. check();
  1445. lua_copy(fromIndex, toIndex);
  1446. }
  1447.  
  1448. /**
  1449. * Returns the number of values on the stack.
  1450. *
  1451. * @return the number of values on the tack
  1452. */
  1453. public synchronized int getTop() {
  1454. check();
  1455. return lua_gettop();
  1456. }
  1457.  
  1458. /**
  1459. * Pushes the length of the value at the specified stack index on the stack.
  1460. * The value pushed by the method corresponds to the Lua <code>#</code>
  1461. * operator.
  1462. *
  1463. * @param index
  1464. * the index for which to push the length
  1465. * @since JNLua 1.0.0
  1466. */
  1467. public synchronized void len(int index) {
  1468. check();
  1469. lua_len(index);
  1470. }
  1471.  
  1472. /**
  1473. * Pops the value on top of the stack inserting it at the specified index
  1474. * and moving up elements above that index.
  1475. *
  1476. * @param index
  1477. * the stack index
  1478. */
  1479. public synchronized void insert(int index) {
  1480. check();
  1481. lua_insert(index);
  1482. }
  1483.  
  1484. /**
  1485. * Pops values from the stack.
  1486. *
  1487. * @param count
  1488. * the number of values to pop
  1489. */
  1490. public synchronized void pop(int count) {
  1491. check();
  1492. lua_pop(count);
  1493. }
  1494.  
  1495. /**
  1496. * Pushes the value at the specified index on top of the stack.
  1497. *
  1498. * @param index
  1499. * the stack index
  1500. */
  1501. public synchronized void pushValue(int index) {
  1502. check();
  1503. lua_pushvalue(index);
  1504. }
  1505.  
  1506. /**
  1507. * Removes the value at the specified stack index moving down elements above
  1508. * that index.
  1509. *
  1510. * @param index
  1511. * the stack index
  1512. */
  1513. public synchronized void remove(int index) {
  1514. check();
  1515. lua_remove(index);
  1516. }
  1517.  
  1518. /**
  1519. * Replaces the value at the specified index with the value popped from the
  1520. * top of the stack.
  1521. *
  1522. * @param index
  1523. * the stack index
  1524. */
  1525. public synchronized void replace(int index) {
  1526. check();
  1527. lua_replace(index);
  1528. }
  1529.  
  1530. /**
  1531. * Sets the specified index as the new top of the stack.
  1532. *
  1533. * <p>
  1534. * The new top of the stack may be above the current top of the stack. In
  1535. * this case, new values are set to <code>nil</code>.
  1536. * </p>
  1537. *
  1538. * @param index
  1539. * the index of the new top of the stack
  1540. */
  1541. public synchronized void setTop(int index) {
  1542. check();
  1543. lua_settop(index);
  1544. }
  1545.  
  1546. // -- Table
  1547. /**
  1548. * Pushes on the stack the value indexed by the key on top of the stack in
  1549. * the table at the specified index. The key is replaced by the value from
  1550. * the table.
  1551. *
  1552. * @param index
  1553. * the stack index containing the table
  1554. */
  1555. public synchronized void getTable(int index) {
  1556. check();
  1557. lua_gettable(index);
  1558. }
  1559.  
  1560. /**
  1561. * Pushes on the stack the value indexed by the specified string key in the
  1562. * table at the specified index.
  1563. *
  1564. * @param index
  1565. * the stack index containing the table
  1566. * @param key
  1567. * the string key
  1568. */
  1569. public synchronized void getField(int index, String key) {
  1570. check();
  1571. lua_getfield(index, key);
  1572. }
  1573.  
  1574. /**
  1575. * Creates a new table and pushes it on the stack.
  1576. */
  1577. public synchronized void newTable() {
  1578. check();
  1579. lua_newtable();
  1580. }
  1581.  
  1582. /**
  1583. * Creates a new table with pre-allocated space for a number of array
  1584. * elements and record elements and pushes it on the stack.
  1585. *
  1586. * @param arrayCount
  1587. * the number of array elements
  1588. * @param recordCount
  1589. * the number of record elements
  1590. */
  1591. public synchronized void newTable(int arrayCount, int recordCount) {
  1592. check();
  1593. lua_createtable(arrayCount, recordCount);
  1594. }
  1595.  
  1596. /**
  1597. * Pops a key from the stack and pushes on the stack the next key and its
  1598. * value in the table at the specified index. If there is no next key, the
  1599. * key is popped but nothing is pushed. The method returns whether there is
  1600. * a next key.
  1601. *
  1602. * @param index
  1603. * the stack index containing the table
  1604. * @return whether there is a next key
  1605. */
  1606. public synchronized boolean next(int index) {
  1607. check();
  1608. return lua_next(index) != 0;
  1609. }
  1610.  
  1611. /**
  1612. * Bypassing metatable logic, pushes on the stack the value indexed by the
  1613. * key on top of the stack in the table at the specified index. The key is
  1614. * replaced by the value from the table.
  1615. *
  1616. * @param index
  1617. * the stack index containing the table
  1618. */
  1619. public synchronized void rawGet(int index) {
  1620. check();
  1621. lua_rawget(index);
  1622. }
  1623.  
  1624. /**
  1625. * Bypassing metatable logic, pushes on the stack the value indexed by the
  1626. * specified integer key in the table at the specified index.
  1627. *
  1628. * @param index
  1629. * the stack index containing the table
  1630. * @param key
  1631. * the integer key
  1632. */
  1633. public synchronized void rawGet(int index, int key) {
  1634. check();
  1635. lua_rawgeti(index, key);
  1636. }
  1637.  
  1638. /**
  1639. * Bypassing metatable logic, sets the value on top of the stack in the
  1640. * table at the specified index using the value on the second highest stack
  1641. * position as the key. Both the value and the key are popped from the
  1642. * stack.
  1643. *
  1644. * @param index
  1645. * the stack index containing the table
  1646. */
  1647. public synchronized void rawSet(int index) {
  1648. check();
  1649. lua_rawset(index);
  1650. }
  1651.  
  1652. /**
  1653. * Bypassing metatable logic, sets the value on top of the stack in the
  1654. * table at the specified index using the specified integer key. The value
  1655. * is popped from the stack.
  1656. *
  1657. * @param index
  1658. * the stack index containing the table
  1659. * @param key
  1660. * the integer key
  1661. */
  1662. public synchronized void rawSet(int index, int key) {
  1663. check();
  1664. lua_rawseti(index, key);
  1665. }
  1666.  
  1667. /**
  1668. * Sets the value on top of the stack in the table at the specified index
  1669. * using the value on the second highest stack position as the key. Both the
  1670. * value and the key are popped from the stack.
  1671. *
  1672. * @param index
  1673. * the stack index containing the table
  1674. */
  1675. public synchronized void setTable(int index) {
  1676. check();
  1677. lua_settable(index);
  1678. }
  1679.  
  1680. /**
  1681. * Sets the value on top of the stack in the table at the specified index
  1682. * using the specified string key. The value is popped from the stack.
  1683. *
  1684. * @param index
  1685. * the stack index containing the table
  1686. * @param key
  1687. * the string key
  1688. */
  1689. public synchronized void setField(int index, String key) {
  1690. check();
  1691. lua_setfield(index, key);
  1692. }
  1693.  
  1694. // -- Metatable
  1695. /**
  1696. * Pushes on the stack the value of the named field in the metatable of the
  1697. * value at the specified index and returns <code>true</code>. If the value
  1698. * does not have a metatable or if the metatable does not contain the named
  1699. * field, nothing is pushed and the method returns <code>false</code>.
  1700. *
  1701. * @param index
  1702. * the stack index containing the value to get the metafield from
  1703. * @param key
  1704. * the string key
  1705. * @return whether the metafield was pushed on the stack
  1706. */
  1707. public synchronized boolean getMetafield(int index, String key) {
  1708. check();
  1709. return lua_getmetafield(index, key) != 0;
  1710. }
  1711.  
  1712. /**
  1713. * Pushes on the stack the metatable of the value at the specified index. If
  1714. * the value does not have a metatable, the method returns
  1715. * <code>false</code> and nothing is pushed.
  1716. *
  1717. * @param index
  1718. * the stack index containing the value to get the metatable from
  1719. * @return whether the metatable was pushed on the stack
  1720. */
  1721. public synchronized boolean getMetatable(int index) {
  1722. check();
  1723. return lua_getmetatable(index) != 0;
  1724. }
  1725.  
  1726. /**
  1727. * Sets the value on top of the stack as the metatable of the value at the
  1728. * specified index. The metatable to be set is popped from the stack
  1729. * regardless whether it can be set or not.
  1730. *
  1731. * @param index
  1732. * the stack index containing the value to set the metatable for
  1733. */
  1734. public synchronized void setMetatable(int index) {
  1735. check();
  1736. lua_setmetatable(index);
  1737. }
  1738.  
  1739. // -- Thread
  1740. /**
  1741. * Pops the start function of a new Lua thread from the stack and creates
  1742. * the new thread with that start function. The new thread is pushed on the
  1743. * stack.
  1744. */
  1745. public synchronized void newThread() {
  1746. check();
  1747. lua_newthread();
  1748. }
  1749.  
  1750. /**
  1751. * Resumes the thread at the specified stack index, popping the specified
  1752. * number of arguments from the top of the stack and passing them to the
  1753. * resumed thread. The method returns the number of values pushed on the
  1754. * stack as the return values of the resumed thread.
  1755. *
  1756. * @param index
  1757. * the stack index containing the thread
  1758. * @param argCount
  1759. * the number of arguments to pass
  1760. * @return the number of values returned by the thread
  1761. */
  1762. public synchronized int resume(int index, int argCount) {
  1763. check();
  1764. return lua_resume(index, argCount);
  1765. }
  1766.  
  1767. /**
  1768. * Returns the status of the thread at the specified stack index. If the
  1769. * thread is in initial state of has finished its execution, the method
  1770. * returns <code>0</code>. If the thread has yielded, the method returns
  1771. * {@link #YIELD}. Other return values indicate errors for which an
  1772. * exception has been thrown.
  1773. *
  1774. * @param index
  1775. * the index
  1776. * @return the status
  1777. */
  1778. public synchronized int status(int index) {
  1779. check();
  1780. return lua_status(index);
  1781. }
  1782.  
  1783. /**
  1784. * Yields the running thread, popping the specified number of values from
  1785. * the top of the stack and passing them as return values to the thread
  1786. * which has resumed the running thread. The method must be used exclusively
  1787. * at the exit point of Java functions, i.e.
  1788. * <code>return luaState.yield(n)</code>.
  1789. *
  1790. * @param returnCount
  1791. * the number of results to pass
  1792. * @return the return value of the Java function
  1793. */
  1794. public synchronized int yield(int returnCount) {
  1795. check();
  1796. yield = true;
  1797. return returnCount;
  1798. }
  1799.  
  1800. // -- Reference
  1801. /**
  1802. * Stores the value on top of the stack in the table at the specified index
  1803. * and returns the integer key of the value in that table as a reference.
  1804. * The value is popped from the stack.
  1805. *
  1806. * @param index
  1807. * the stack index containing the table where to store the value
  1808. * @return the reference integer key
  1809. * @see #unref(int, int)
  1810. */
  1811. public synchronized int ref(int index) {
  1812. check();
  1813. return lua_ref(index);
  1814.  
  1815. }
  1816.  
  1817. /**
  1818. * Removes a previously created reference from the table at the specified
  1819. * index. The value is removed from the table and its integer key of the
  1820. * reference is freed for reuse.
  1821. *
  1822. * @param index
  1823. * the stack index containing the table where the value was
  1824. * stored
  1825. * @param reference
  1826. * the reference integer key
  1827. * @see #ref(int)
  1828. */
  1829. public synchronized void unref(int index, int reference) {
  1830. check();
  1831. lua_unref(index, reference);
  1832. }
  1833.  
  1834. // -- Optimization
  1835. /**
  1836. * Counts the number of entries in a table.
  1837. *
  1838. * <p>
  1839. * The method provides optimized performance over a Java implementation of
  1840. * the same functionality due to the reduced number of JNI transitions.
  1841. * </p>
  1842. *
  1843. * @param index
  1844. * the stack index containing the table
  1845. * @return the number of entries in the table
  1846. */
  1847. public synchronized int tableSize(int index) {
  1848. check();
  1849. return lua_tablesize(index);
  1850. }
  1851.  
  1852. /**
  1853. * Moves the specified number of sequential elements in a table used as an
  1854. * array from one index to another.
  1855. *
  1856. * <p>
  1857. * The method provides optimized performance over a Java implementation of
  1858. * the same functionality due to the reduced number of JNI transitions.
  1859. * </p>
  1860. *
  1861. * @param index
  1862. * the stack index containing the table
  1863. * @param from
  1864. * the index to move from
  1865. * @param to
  1866. * the index to move to
  1867. * @param count
  1868. * the number of elements to move
  1869. */
  1870. public synchronized void tableMove(int index, int from, int to, int count) {
  1871. check();
  1872. lua_tablemove(index, from, to, count);
  1873. }
  1874.  
  1875. // -- Argument checking
  1876. /**
  1877. * Checks if a condition is true for the specified function argument. If
  1878. * not, the method throws a Lua runtime exception with the specified error
  1879. * message.
  1880. *
  1881. * @param index
  1882. * the argument index
  1883. * @param condition
  1884. * the condition
  1885. * @param msg
  1886. * the error message
  1887. */
  1888. public synchronized void checkArg(int index, boolean condition, String msg) {
  1889. check();
  1890. if (!condition) {
  1891. throw getArgException(index, msg);
  1892. }
  1893. }
  1894.  
  1895. /**
  1896. * Checks if the value of the specified function argument is a string or a
  1897. * number. If so, the argument value is returned as a byte array. Otherwise,
  1898. * the method throws a Lua runtime exception with a descriptive error
  1899. * message.
  1900. *
  1901. * @param index
  1902. * the argument index
  1903. * @return the byte array value
  1904. */
  1905. public synchronized byte[] checkByteArray(int index) {
  1906. check();
  1907. if (!isString(index)) {
  1908. throw getArgTypeException(index, LuaType.STRING);
  1909. }
  1910. return toByteArray(index);
  1911. }
  1912.  
  1913. /**
  1914. * Checks if the value of the specified function argument is a string or a
  1915. * number. If so, the argument value is returned as a byte array. If the
  1916. * value of the specified argument is undefined or <code>nil</code>, the
  1917. * method returns the specified default value. Otherwise, the method throws
  1918. * a Lua runtime exception with a descriptive error message.
  1919. *
  1920. * @param index
  1921. * the argument index
  1922. * @param d
  1923. * the default value
  1924. * @return the string value, or the default value
  1925. */
  1926. public synchronized byte[] checkByteArray(int index, byte[] d) {
  1927. check();
  1928. if (isNoneOrNil(index)) {
  1929. return d;
  1930. }
  1931. return checkByteArray(index);
  1932. }
  1933.  
  1934. /**
  1935. * Checks if the value of the specified function argument is a string or a
  1936. * number matching the name of one of the specified enum values. If so, the
  1937. * argument value is returned as an enum value. Otherwise, the method throws
  1938. * a Lua runtime exception with a descriptive error message.
  1939. *
  1940. * @param index
  1941. * the argument index
  1942. * @param values
  1943. * the enum values
  1944. * @return the string value
  1945. * @since JNLua 1.0.0
  1946. */
  1947. public synchronized <T extends Enum<T>> T checkEnum(int index, T[] values) {
  1948. check();
  1949. return checkEnum(index, values, null);
  1950. }
  1951.  
  1952. /**
  1953. * Checks if the value of the specified function argument is a string or a
  1954. * number matching one of the specified enum values. If so, the argument
  1955. * value is returned as an enum value. If the specified stack index is
  1956. * non-valid or if its value is <code>nil</code>, the method returns the
  1957. * specified default value. Otherwise, the method throws a Lua runtime
  1958. * exception with a descriptive error message.
  1959. *
  1960. * @param index
  1961. * the argument index
  1962. * @param values
  1963. * the enum values
  1964. * @param d
  1965. * the default value
  1966. * @return the string value, or the default value
  1967. * @since JNLua 1.0.0
  1968. */
  1969. public synchronized <T extends Enum<T>> T checkEnum(int index, T[] values,
  1970. T d) {
  1971. check();
  1972. String s = d != null ? checkString(index, d.name())
  1973. : checkString(index);
  1974. for (int i = 0; i < values.length; i++) {
  1975. if (values[i].name().equals(s)) {
  1976. return values[i];
  1977. }
  1978. }
  1979. throw getArgException(index, String.format("invalid option '%s'", s));
  1980. }
  1981.  
  1982. /**
  1983. * Checks if the value of the specified function argument is a boolean. If
  1984. * so, the argument value is returned as a boolean. Otherwise, the method
  1985. * throws a Lua runtime exception with a descriptive error message.
  1986. *
  1987. * @param index
  1988. * the argument index
  1989. * @return the integer value
  1990. */
  1991. public synchronized boolean checkBoolean(int index) {
  1992. check();
  1993. if (!isBoolean(index)) {
  1994. throw getArgTypeException(index, LuaType.BOOLEAN);
  1995. }
  1996. return toBoolean(index);
  1997. }
  1998.  
  1999. /**
  2000. * Checks if the value of the specified function argument is a number or a
  2001. * string convertible to a number. If so, the argument value is returned as
  2002. * an integer. Otherwise, the method throws a Lua runtime exception with a
  2003. * descriptive error message.
  2004. *
  2005. * @param index
  2006. * the argument index
  2007. * @return the integer value
  2008. */
  2009. public synchronized int checkInteger(int index) {
  2010. check();
  2011. Integer integer = toIntegerX(index);
  2012. if (integer == null) {
  2013. throw getArgTypeException(index, LuaType.NUMBER);
  2014. }
  2015. return integer.intValue();
  2016. }
  2017.  
  2018. /**
  2019. * Checks if the value of the specified function argument is a number or a
  2020. * string convertible to a number. If so, the argument value is returned as
  2021. * an integer. If the specified stack index is non-valid or if its value is
  2022. * <code>nil</code>, the method returns the specified default value.
  2023. * Otherwise, the method throws a Lua runtime exception with a descriptive
  2024. * error message.
  2025. *
  2026. * @param index
  2027. * the argument index
  2028. * @param d
  2029. * the default value
  2030. * @return the integer value, or the default value
  2031. */
  2032. public synchronized int checkInteger(int index, int d) {
  2033. check();
  2034. if (isNoneOrNil(index)) {
  2035. return d;
  2036. }
  2037. return checkInteger(index);
  2038. }
  2039.  
  2040. /**
  2041. * Checks if the value of the specified function argument is convertible to
  2042. * a Java object of the specified type. If so, the argument value is
  2043. * returned as a Java object of the specified type. Otherwise, the method
  2044. * throws a Lua runtime exception with a descriptive error message.
  2045. *
  2046. * <p>
  2047. * Note that the converter converts <code>nil</code> to <code>null</code>.
  2048. * Therefore, the method may return <code>null</code> if the value is
  2049. * <code>nil</code>.
  2050. * </p>
  2051. *
  2052. * @param index
  2053. * the argument index
  2054. * @param clazz
  2055. * the expected type
  2056. * @return the Java object, or <code>null</code>
  2057. */
  2058. public synchronized <T> T checkJavaObject(int index, Class<T> clazz) {
  2059. check();
  2060. if (!isJavaObject(index, clazz)) {
  2061. checkArg(
  2062. index,
  2063. false,
  2064. String.format("%s expected, got %s",
  2065. clazz.getCanonicalName(), typeName(index)));
  2066. }
  2067. return toJavaObject(index, clazz);
  2068. }
  2069.  
  2070. /**
  2071. * Checks if the value of the specified function argument is convertible to
  2072. * a Java object of the specified type. If so, the argument value is
  2073. * returned as a Java object of the specified type. If the specified stack
  2074. * index is non-valid or if its value is <code>nil</code>, the method
  2075. * returns the specified default value. Otherwise, the method throws a Lua
  2076. * runtime exception with a descriptive error message.
  2077. *
  2078. * @param index
  2079. * the argument index
  2080. * @param clazz
  2081. * the expected class
  2082. * @param d
  2083. * the default value
  2084. * @return the Java object, or the default value
  2085. */
  2086. public synchronized <T> T checkJavaObject(int index, Class<T> clazz, T d) {
  2087. check();
  2088. if (isNoneOrNil(index)) {
  2089. return d;
  2090. }
  2091. return checkJavaObject(index, clazz);
  2092. }
  2093.  
  2094. /**
  2095. * Checks if the value of the specified function argument is a number or a
  2096. * string convertible to a number. If so, the argument value is returned as
  2097. * a number. Otherwise, the method throws a Lua runtime exception with a
  2098. * descriptive error message.
  2099. *
  2100. * @param index
  2101. * the argument index
  2102. * @return the number value
  2103. */
  2104. public synchronized double checkNumber(int index) {
  2105. check();
  2106. Double number = toNumberX(index);
  2107. if (number == null) {
  2108. throw getArgTypeException(index, LuaType.NUMBER);
  2109. }
  2110. return number.doubleValue();
  2111. }
  2112.  
  2113. /**
  2114. * Checks if the value of the specified function argument is a number or a
  2115. * string convertible to a number. If so, the argument value is returned as
  2116. * a number. If the specified stack index is non-valid or if its value is
  2117. * <code>nil</code>, the method returns the specified default value.
  2118. * Otherwise, the method throws a Lua runtime exception with a descriptive
  2119. * error message.
  2120. *
  2121. * @param index
  2122. * the argument index
  2123. * @param d
  2124. * the default value
  2125. * @return the number value, or the default value
  2126. */
  2127. public synchronized double checkNumber(int index, double d) {
  2128. check();
  2129. if (isNoneOrNil(index)) {
  2130. return d;
  2131. }
  2132. return checkNumber(index);
  2133. }
  2134.  
  2135. /**
  2136. * Checks if the value of the specified function argument is a string or a
  2137. * number matching one of the specified options. If so, the index position
  2138. * of the matched option is returned. Otherwise, the method throws a Lua
  2139. * runtime exception with a descriptive error message.
  2140. *
  2141. * @param index
  2142. * the argument index
  2143. * @param options
  2144. * the options
  2145. * @return the index position of the matched option
  2146. */
  2147. public synchronized int checkOption(int index, String[] options) {
  2148. check();
  2149. return checkOption(index, options, null);
  2150. }
  2151.  
  2152. /**
  2153. * Checks if the value of the specified function argument is a string or a
  2154. * number matching one of the specified options. If so, the index position
  2155. * of the matched option is returned. If the specified stack index is
  2156. * non-valid or if its value is <code>nil</code>, the method matches the
  2157. * specified default value. If no match is found, the method throws a Lua
  2158. * runtime exception with a descriptive error message.
  2159. *
  2160. * @param index
  2161. * the argument index
  2162. * @param options
  2163. * the options
  2164. * @param d
  2165. * the default value
  2166. * @return the index position of the matched option
  2167. */
  2168. public synchronized int checkOption(int index, String[] options, String d) {
  2169. check();
  2170. String s = d != null ? checkString(index, d) : checkString(index);
  2171. for (int i = 0; i < options.length; i++) {
  2172. if (options[i].equals(s)) {
  2173. return i;
  2174. }
  2175. }
  2176. throw getArgException(index, String.format("invalid option '%s'", s));
  2177. }
  2178.  
  2179. /**
  2180. * Checks if the value of the specified function argument is a string or a
  2181. * number. If so, the argument value is returned as a string. Otherwise, the
  2182. * method throws a Lua runtime exception with a descriptive error message.
  2183. *
  2184. * @param index
  2185. * the argument index
  2186. * @return the string value
  2187. */
  2188. public synchronized String checkString(int index) {
  2189. check();
  2190. if (!isString(index)) {
  2191. throw getArgTypeException(index, LuaType.STRING);
  2192. }
  2193. return toString(index);
  2194. }
  2195.  
  2196. /**
  2197. * Checks if the value of the specified function argument is a string or a
  2198. * number. If so, the argument value is returned as a string. If the
  2199. * specified stack index is non-valid or if its value is <code>nil</code>,
  2200. * the method returns the specified default value. Otherwise, the method
  2201. * throws a Lua runtime exception with a descriptive error message.
  2202. *
  2203. * @param index
  2204. * the argument index
  2205. * @param d
  2206. * the default value
  2207. * @return the string value, or the default value
  2208. */
  2209. public synchronized String checkString(int index, String d) {
  2210. check();
  2211. if (isNoneOrNil(index)) {
  2212. return d;
  2213. }
  2214. return checkString(index);
  2215. }
  2216.  
  2217. /**
  2218. * Checks if the value of the specified function argument is of the
  2219. * specified type. If not, the method throws a Lua runtime exception with a
  2220. * descriptive error message.
  2221. *
  2222. * @param index
  2223. * the argument index
  2224. * @param type
  2225. * the type
  2226. */
  2227. public synchronized void checkType(int index, LuaType type) {
  2228. check();
  2229. if (type(index) != type) {
  2230. throw getArgTypeException(index, type);
  2231. }
  2232. }
  2233.  
  2234. // -- Proxy
  2235. /**
  2236. * Returns a proxy object for the Lua value at the specified index.
  2237. *
  2238. * @param index
  2239. * the stack index containing the Lua value
  2240. * @return the Lua value proxy
  2241. */
  2242. public synchronized LuaValueProxy getProxy(int index) {
  2243. check();
  2244. pushValue(index);
  2245. return new LuaValueProxyImpl(ref(REGISTRYINDEX()));
  2246. }
  2247.  
  2248. /**
  2249. * Returns a proxy object implementing the specified interface in Lua. The
  2250. * table at the specified stack index contains the method names from the
  2251. * interface as keys and the Lua functions implementing the interface
  2252. * methods as values. The returned object always implements the
  2253. * {@link LuaValueProxy} interface in addition to the specified interface.
  2254. *
  2255. * @param index
  2256. * the stack index containing the table
  2257. * @param interfaze
  2258. * the interface
  2259. * @return the proxy object
  2260. */
  2261. @SuppressWarnings("unchecked")
  2262. public synchronized <T> T getProxy(int index, Class<T> interfaze) {
  2263. check();
  2264. return (T) getProxy(index, new Class<?>[] { interfaze });
  2265. }
  2266.  
  2267. /**
  2268. * Returns a proxy object implementing the specified list of interfaces in
  2269. * Lua. The table at the specified stack index contains the method names
  2270. * from the interfaces as keys and the Lua functions implementing the
  2271. * interface methods as values. The returned object always implements the
  2272. * {@link LuaValueProxy} interface in addition to the specified interfaces.
  2273. *
  2274. * @param index
  2275. * the stack index containing the table
  2276. * @param interfaces
  2277. * the interfaces
  2278. * @return the proxy object
  2279. */
  2280. public synchronized LuaValueProxy getProxy(int index, Class<?>[] interfaces) {
  2281. check();
  2282. pushValue(index);
  2283. if (!isTable(index)) {
  2284. throw new IllegalArgumentException(String.format(
  2285. "index %d is not a table", index));
  2286. }
  2287. Class<?>[] allInterfaces = new Class<?>[interfaces.length + 1];
  2288. System.arraycopy(interfaces, 0, allInterfaces, 0, interfaces.length);
  2289. allInterfaces[allInterfaces.length - 1] = LuaValueProxy.class;
  2290. int reference = ref(REGISTRYINDEX());
  2291. try {
  2292. Object proxy = Proxy.newProxyInstance(classLoader, allInterfaces,
  2293. new LuaInvocationHandler(reference));
  2294. reference = -1;
  2295. return (LuaValueProxy) proxy;
  2296. } finally {
  2297. if (reference >= 0) {
  2298. unref(REGISTRYINDEX(), reference);
  2299. }
  2300. }
  2301. }
  2302.  
  2303. // -- Private methods
  2304. /**
  2305. * Returns whether this Lua state is open.
  2306. */
  2307. private boolean isOpenInternal() {
  2308. return luaState != 0L;
  2309. }
  2310.  
  2311. /**
  2312. * Closes this Lua state.
  2313. */
  2314. private void closeInternal() {
  2315. if (isOpenInternal()) {
  2316. lua_close(ownState);
  2317. if (isOpenInternal()) {
  2318. throw new IllegalStateException("cannot close");
  2319. }
  2320. }
  2321. }
  2322.  
  2323. /**
  2324. * Checks this Lua state.
  2325. */
  2326. private void check() {
  2327. // Check open
  2328. if (!isOpenInternal()) {
  2329. throw new IllegalStateException("Lua state is closed");
  2330. }
  2331.  
  2332. // Check proxy queue
  2333. LuaValueProxyRef luaValueProxyRef;
  2334. while ((luaValueProxyRef = (LuaValueProxyRef) proxyQueue.poll()) != null) {
  2335. proxySet.remove(luaValueProxyRef);
  2336. lua_unref(REGISTRYINDEX(), luaValueProxyRef.getReference());
  2337. }
  2338. }
  2339.  
  2340. /**
  2341. * Creates a Lua runtime exception to indicate an argument type error.
  2342. */
  2343. private LuaRuntimeException getArgTypeException(int index, LuaType type) {
  2344. final LuaType have = type(index);
  2345. return getArgException(index,
  2346. String.format("%s expected, got %s", type.toString()
  2347. .toLowerCase(), have != null ? type(index).toString().toLowerCase() : "none"));
  2348. }
  2349.  
  2350. /**
  2351. * Creates a Lua runtime exception to indicate an argument error.
  2352. *
  2353. * @param extraMsg
  2354. * @return
  2355. */
  2356. private LuaRuntimeException getArgException(int index, String extraMsg) {
  2357. check();
  2358.  
  2359. // Get execution point
  2360. String name = null, nameWhat = null;
  2361. LuaDebug luaDebug = lua_getstack(0);
  2362. if (luaDebug != null) {
  2363. lua_getinfo("n", luaDebug);
  2364. name = luaDebug.getName();
  2365. nameWhat = luaDebug.getNameWhat();
  2366. }
  2367.  
  2368. // Adjust for methods
  2369. if ("method".equals(nameWhat)) {
  2370. index--;
  2371. }
  2372.  
  2373. // Format message
  2374. String msg;
  2375. String argument = index > 0 ? String.format("argument #%d", index)
  2376. : "self argument";
  2377. if (name != null) {
  2378. msg = String
  2379. .format("bad %s to '%s' (%s)", argument, name, extraMsg);
  2380. } else {
  2381. msg = String.format("bad %s (%s)", argument, extraMsg);
  2382. }
  2383. return new LuaRuntimeException(msg);
  2384. }
  2385.  
  2386. /**
  2387. * Validates a value specified as the new maximum allowed memory use. This
  2388. * is used in particular to validate values passed to the constructor.
  2389. *
  2390. * @param value
  2391. * the value to validate
  2392. * @return the value itself
  2393. */
  2394. private static int validateMemory(int value) {
  2395. if (value < 1) {
  2396. throw new IllegalArgumentException("Maximum memory must be larger than zero.");
  2397. }
  2398. return value;
  2399. }
  2400.  
  2401. // -- Native methods
  2402. public static native int lua_registryindex();
  2403.  
  2404. public static native String lua_version();
  2405.  
  2406. protected native void lua_newstate(int apiversion, long luaState);
  2407.  
  2408. protected native void lua_close(boolean ownState);
  2409.  
  2410. protected native int lua_gc(int what, int data);
  2411.  
  2412. protected native void lua_openlib(int lib);
  2413.  
  2414. protected native void lua_load(InputStream inputStream, String chunkname,
  2415. String mode) throws IOException;
  2416.  
  2417. protected native void lua_dump(OutputStream outputStream) throws IOException;
  2418.  
  2419. protected native void lua_pcall(int nargs, int nresults);
  2420.  
  2421. protected native void lua_getglobal(String name);
  2422.  
  2423. protected native void lua_setglobal(String name);
  2424.  
  2425. protected native void lua_pushboolean(int b);
  2426.  
  2427. protected native void lua_pushbytearray(byte[] b);
  2428.  
  2429. protected native void lua_pushinteger(int n);
  2430.  
  2431. protected native void lua_pushjavafunction(JavaFunction f);
  2432.  
  2433. protected native void lua_pushjavaobject(Object object);
  2434.  
  2435. protected native void lua_pushnil();
  2436.  
  2437. protected native void lua_pushnumber(double n);
  2438.  
  2439. protected native void lua_pushstring(String s);
  2440.  
  2441. protected native int lua_isboolean(int index);
  2442.  
  2443. protected native int lua_iscfunction(int index);
  2444.  
  2445. protected native int lua_isfunction(int index);
  2446.  
  2447. protected native int lua_isjavafunction(int index);
  2448.  
  2449. protected native int lua_isjavaobject(int index);
  2450.  
  2451. protected native int lua_isnil(int index);
  2452.  
  2453. protected native int lua_isnone(int index);
  2454.  
  2455. protected native int lua_isnoneornil(int index);
  2456.  
  2457. protected native int lua_isnumber(int index);
  2458.  
  2459. protected native int lua_isstring(int index);
  2460.  
  2461. protected native int lua_istable(int index);
  2462.  
  2463. protected native int lua_isthread(int index);
  2464.  
  2465. protected native int lua_compare(int index1, int index2, int operator);
  2466.  
  2467. protected native int lua_rawequal(int index1, int index2);
  2468.  
  2469. protected native int lua_rawlen(int index);
  2470.  
  2471. protected native int lua_toboolean(int index);
  2472.  
  2473. protected native byte[] lua_tobytearray(int index);
  2474.  
  2475. protected native int lua_tointeger(int index);
  2476.  
  2477. protected native Integer lua_tointegerx(int index);
  2478.  
  2479. protected native JavaFunction lua_tojavafunction(int index);
  2480.  
  2481. protected native Object lua_tojavaobject(int index);
  2482.  
  2483. protected native double lua_tonumber(int index);
  2484.  
  2485. protected native Double lua_tonumberx(int index);
  2486.  
  2487. protected native long lua_topointer(int index);
  2488.  
  2489. protected native String lua_tostring(int index);
  2490.  
  2491. protected native int lua_type(int index);
  2492.  
  2493. protected native int lua_absindex(int index);
  2494.  
  2495. protected native int lua_arith(int operator);
  2496.  
  2497. protected native void lua_concat(int n);
  2498.  
  2499. protected native int lua_copy(int fromIndex, int toIndex);
  2500.  
  2501. protected native int lua_gettop();
  2502.  
  2503. protected native void lua_len(int index);
  2504.  
  2505. protected native void lua_insert(int index);
  2506.  
  2507. protected native void lua_pop(int n);
  2508.  
  2509. protected native void lua_pushvalue(int index);
  2510.  
  2511. protected native void lua_remove(int index);
  2512.  
  2513. protected native void lua_replace(int index);
  2514.  
  2515. protected native void lua_settop(int index);
  2516.  
  2517. protected native void lua_createtable(int narr, int nrec);
  2518.  
  2519. protected native int lua_getsubtable(int idx, String fname);
  2520.  
  2521. protected native void lua_gettable(int index);
  2522.  
  2523. protected native void lua_getfield(int index, String k);
  2524.  
  2525. protected native void lua_newtable();
  2526.  
  2527. protected native int lua_next(int index);
  2528.  
  2529. protected native void lua_rawget(int index);
  2530.  
  2531. protected native void lua_rawgeti(int index, int n);
  2532.  
  2533. protected native void lua_rawset(int index);
  2534.  
  2535. protected native void lua_rawseti(int index, int n);
  2536.  
  2537. protected native void lua_settable(int index);
  2538.  
  2539. protected native void lua_setfield(int index, String k);
  2540.  
  2541. protected native int lua_getmetatable(int index);
  2542.  
  2543. protected native void lua_setmetatable(int index);
  2544.  
  2545. protected native int lua_getmetafield(int index, String k);
  2546.  
  2547. protected native void lua_newthread();
  2548.  
  2549. protected native int lua_resume(int index, int nargs);
  2550.  
  2551. protected native int lua_status(int index);
  2552.  
  2553. protected native int lua_getcoroutinemem();
  2554.  
  2555. protected native int lua_ref(int index);
  2556.  
  2557. protected native void lua_unref(int index, int ref);
  2558.  
  2559. protected native LuaDebug lua_getstack(int level);
  2560.  
  2561. protected native int lua_getinfo(String what, LuaDebug ar);
  2562.  
  2563. protected native int lua_tablesize(int index);
  2564.  
  2565. protected native void lua_tablemove(int index, int from, int to, int count);
  2566.  
  2567. // -- Enumerated types
  2568. /**
  2569. * Represents a Lua library.
  2570. */
  2571. public enum Library {
  2572. /*
  2573. * The order of the libraries follows the definition in linit.c.
  2574. */
  2575. /**
  2576. * The base library.
  2577. */
  2578. BASE,
  2579.  
  2580. /**
  2581. * The package library.
  2582. */
  2583. PACKAGE,
  2584.  
  2585. /**
  2586. * The coroutine library.
  2587. *
  2588. * @since JNLua 1.0.0
  2589. */
  2590. COROUTINE,
  2591.  
  2592. /**
  2593. * The table library.
  2594. */
  2595. TABLE,
  2596.  
  2597. /**
  2598. * The IO library.
  2599. */
  2600. IO,
  2601.  
  2602. /**
  2603. * The OS library.
  2604. */
  2605. OS,
  2606.  
  2607. /**
  2608. * The string library.
  2609. */
  2610. STRING,
  2611.  
  2612. /**
  2613. * The bit32 library.
  2614. *
  2615. * @since JNLua 1.0.0
  2616. */
  2617. BIT32,
  2618.  
  2619. /**
  2620. * The math library.
  2621. */
  2622. MATH,
  2623.  
  2624. /**
  2625. * The debug library.
  2626. */
  2627. DEBUG,
  2628.  
  2629. /**
  2630. * The persistence library.
  2631. */
  2632. ERIS,
  2633.  
  2634. /**
  2635. * The UTF-8 library.
  2636. *
  2637. * @since JNLua 1.1.0
  2638. */
  2639. UTF8,
  2640.  
  2641. /**
  2642. * The Java library.
  2643. */
  2644. JAVA {
  2645. @Override
  2646. void open(LuaState luaState) {
  2647. JavaModule.getInstance().open(luaState);
  2648. }
  2649. };
  2650.  
  2651. // -- Methods
  2652. /**
  2653. * Opens this library.
  2654. */
  2655. void open(LuaState luaState) {
  2656. luaState.lua_openlib(ordinal());
  2657. }
  2658. }
  2659.  
  2660. /**
  2661. * Represents a Lua garbage collector action. Please see the Lua Reference
  2662. * Manual for an explanation of these actions.
  2663. */
  2664. public enum GcAction {
  2665. /**
  2666. * Stop.
  2667. */
  2668. STOP,
  2669.  
  2670. /**
  2671. * Restart.
  2672. */
  2673. RESTART,
  2674.  
  2675. /**
  2676. * Collect.
  2677. */
  2678. COLLECT,
  2679.  
  2680. /**
  2681. * Count memory in kilobytes.
  2682. */
  2683. COUNT,
  2684.  
  2685. /**
  2686. * Count reminder in bytes.
  2687. */
  2688. COUNTB,
  2689.  
  2690. /**
  2691. * Step.
  2692. */
  2693. STEP,
  2694.  
  2695. /**
  2696. * Set pause.
  2697. */
  2698. SETPAUSE,
  2699.  
  2700. /**
  2701. * Set step multiplier.
  2702. */
  2703. SETSTEPMUL,
  2704.  
  2705. /**
  2706. * Undocumented.
  2707. *
  2708. * @since JNLua 1.0.0
  2709. */
  2710. SETMAJORINC,
  2711.  
  2712. /**
  2713. * Returns whether the collector is running (i.e. not stopped).
  2714. *
  2715. * @since JNLua 1.0.0
  2716. */
  2717. ISRUNNING,
  2718.  
  2719. /**
  2720. * Changes the collector to the generational mode.
  2721. *
  2722. * @since JNLua 1.0.0
  2723. */
  2724. GEN,
  2725.  
  2726. /**
  2727. * Changes the collector to the incremental mode.
  2728. *
  2729. * @since JNLua 1.0.0
  2730. */
  2731. INC
  2732. }
  2733.  
  2734. /**
  2735. * Represents a Lua arithmetic operator. Please see the Lua Reference Manual
  2736. * for an explanation of these operators.
  2737. *
  2738. * @since JNLua 1.0.0
  2739. */
  2740. public enum ArithOperator {
  2741. /**
  2742. * Addition operator.
  2743. */
  2744. ADD,
  2745.  
  2746. /**
  2747. * Subtraction operator.
  2748. */
  2749. SUB,
  2750.  
  2751. /**
  2752. * Multiplication operator.
  2753. */
  2754. MUL,
  2755.  
  2756. /**
  2757. * Division operator.
  2758. */
  2759. DIV,
  2760.  
  2761. /**
  2762. * Modulo operator.
  2763. */
  2764. MOD,
  2765.  
  2766. /**
  2767. * Exponentiation operator.
  2768. */
  2769. POW,
  2770.  
  2771. /**
  2772. * Mathematical negation operator.
  2773. */
  2774. UNM
  2775. }
  2776.  
  2777. /**
  2778. * Represents a Lua relational operator. Please see the Lua Reference Manual
  2779. * for an explanation of these operators.
  2780. *
  2781. * @since JNLua 1.0.0
  2782. */
  2783. public enum RelOperator {
  2784. /**
  2785. * Equality operator.
  2786. */
  2787. EQ,
  2788.  
  2789. /**
  2790. * Less than operator.
  2791. */
  2792. LT,
  2793.  
  2794. /**
  2795. * Less or equal operator.
  2796. */
  2797. LE
  2798. }
  2799.  
  2800. // -- Nested types
  2801. /**
  2802. * Phantom reference to a Lua value proxy for pre-mortem cleanup.
  2803. */
  2804. private static class LuaValueProxyRef extends
  2805. PhantomReference<LuaValueProxyImpl> {
  2806. // -- State
  2807. private int reference;
  2808.  
  2809. // --Construction
  2810. /**
  2811. * Creates a new instance.
  2812. */
  2813. public LuaValueProxyRef(LuaValueProxyImpl luaProxyImpl, int reference) {
  2814. super(luaProxyImpl, luaProxyImpl.getLuaState().proxyQueue);
  2815. this.reference = reference;
  2816. }
  2817.  
  2818. // -- Properties
  2819. /**
  2820. * Returns the reference.
  2821. */
  2822. public int getReference() {
  2823. return reference;
  2824. }
  2825. }
  2826.  
  2827. /**
  2828. * Lua value proxy implementation.
  2829. */
  2830. private class LuaValueProxyImpl implements LuaValueProxy {
  2831. // -- State
  2832. private int reference;
  2833.  
  2834. // -- Construction
  2835. /**
  2836. * Creates a new instance.
  2837. */
  2838. public LuaValueProxyImpl(int reference) {
  2839. this.reference = reference;
  2840. proxySet.add(new LuaValueProxyRef(this, reference));
  2841. }
  2842.  
  2843. // -- LuaProxy methods
  2844. @Override
  2845. public LuaState getLuaState() {
  2846. return LuaState.this;
  2847. }
  2848.  
  2849. @Override
  2850. public void pushValue() {
  2851. synchronized (LuaState.this) {
  2852. rawGet(REGISTRYINDEX(), reference);
  2853. }
  2854. }
  2855. }
  2856.  
  2857. /**
  2858. * Invocation handler for implementing Java interfaces in Lua.
  2859. */
  2860. private class LuaInvocationHandler extends LuaValueProxyImpl implements
  2861. InvocationHandler {
  2862. // -- Construction
  2863. /**
  2864. * Creates a new instance.
  2865. */
  2866. public LuaInvocationHandler(int reference) {
  2867. super(reference);
  2868. }
  2869.  
  2870. // -- InvocationHandler methods
  2871. @Override
  2872. public Object invoke(Object proxy, Method method, Object[] args)
  2873. throws Throwable {
  2874. // Handle LuaProxy methods
  2875. if (method.getDeclaringClass() == LuaValueProxy.class) {
  2876. return method.invoke(this, args);
  2877. }
  2878.  
  2879. // Handle Lua calls
  2880. synchronized (LuaState.this) {
  2881. pushValue();
  2882. getField(-1, method.getName());
  2883. if (!isFunction(-1)) {
  2884. pop(2);
  2885. throw new UnsupportedOperationException(method.getName());
  2886. }
  2887. insert(-2);
  2888. int argCount = args != null ? args.length : 0;
  2889. for (int i = 0; i < argCount; i++) {
  2890. pushJavaObject(args[i]);
  2891. }
  2892. int retCount = method.getReturnType() != Void.TYPE ? 1 : 0;
  2893. call(argCount + 1, retCount);
  2894. try {
  2895. return retCount == 1 ? LuaState.this.toJavaObject(-1,
  2896. method.getReturnType()) : null;
  2897. } finally {
  2898. if (retCount == 1) {
  2899. pop(1);
  2900. }
  2901. }
  2902. }
  2903. }
  2904. }
  2905.  
  2906. /**
  2907. * Lua debug structure.
  2908. */
  2909. protected static class LuaDebug {
  2910. /**
  2911. * The <code>lua_Debug</code> pointer on the JNI side. <code>0</code>
  2912. * implies that the activation record has been freed. The field is
  2913. * modified exclusively on the JNI side and must not be touched on the
  2914. * Java side.
  2915. */
  2916. private long luaDebug;
  2917.  
  2918. /**
  2919. * Ensures proper finalization of this Lua debug structure.
  2920. */
  2921. private Object finalizeGuardian;
  2922.  
  2923. /**
  2924. * Creates a new instance.
  2925. */
  2926. protected LuaDebug(long luaDebug, boolean ownDebug) {
  2927. this.luaDebug = luaDebug;
  2928. if (ownDebug) {
  2929. finalizeGuardian = new Object() {
  2930. @Override
  2931. public void finalize() {
  2932. synchronized (LuaDebug.this) {
  2933. lua_debugfree();
  2934. }
  2935. }
  2936. };
  2937. }
  2938. }
  2939.  
  2940. // -- Properties
  2941. /**
  2942. * Returns a reasonable name for the function given by this activation
  2943. * record, or <code>null</code> if none is found.
  2944. */
  2945. public String getName() {
  2946. return lua_debugname();
  2947. }
  2948.  
  2949. /**
  2950. * Explains the name of the function given by this activation record.
  2951. */
  2952. public String getNameWhat() {
  2953. return lua_debugnamewhat();
  2954. }
  2955.  
  2956. // -- Native methods
  2957. protected native void lua_debugfree();
  2958.  
  2959. protected native String lua_debugname();
  2960.  
  2961. protected native String lua_debugnamewhat();
  2962. }
  2963. }
Advertisement
Add Comment
Please, Sign In to add comment