### Build LuaJIT with custom C compiler flags Source: https://github.com/scoder/lupa/blob/master/INSTALL.rst Example command to compile LuaJIT while passing specific C compiler flags to the `make` utility. This is useful for custom build environments or specific optimizations. ```Shell make CFLAGS="..." ``` -------------------------------- ### Build Lupa extension module using Python setup.py Source: https://github.com/scoder/lupa/blob/master/INSTALL.rst Command to build the Lupa Python extension module in-place using `setup.py`'s `build_ext` target. This compiles the necessary C/Cython components. ```Shell python setup.py build_ext -i ``` -------------------------------- ### Build LuaJIT from source Source: https://github.com/scoder/lupa/blob/master/INSTALL.rst Commands to navigate to the LuaJIT source directory and compile it using `make`. This is a prerequisite for building Lupa with LuaJIT. ```Shell cd LuaJIT-2.0.2 make cd .. ``` -------------------------------- ### Install Lupa via pip after Lua 5.2 dev setup (Debian/Ubuntu) Source: https://github.com/scoder/lupa/blob/master/INSTALL.rst After installing Lua 5.2 development packages, this command installs the Lupa library using the Python package installer `pip` on Debian or Ubuntu. ```Shell pip install lupa ``` -------------------------------- ### Build Lupa with bundled Lua 5.x and Cython Source: https://github.com/scoder/lupa/blob/master/INSTALL.rst Command to build Lupa using the bundled Lua 5.x runtime and Cython, creating a wheel distribution. The `--use-bundle` and `--with-cython` flags specify the build configuration. ```Shell python3 setup.py bdist_wheel --use-bundle --with-cython ``` -------------------------------- ### Initialize and update Lua 5.x submodule for Lupa Source: https://github.com/scoder/lupa/blob/master/INSTALL.rst Command to clone and update the bundled Lua 5.x submodule, which provides the standard Lua runtime for building Lupa without LuaJIT. ```Shell git submodule update --init third-party/lua ``` -------------------------------- ### Install Lupa via pip after LuaJIT2 dev setup (Debian/Ubuntu) Source: https://github.com/scoder/lupa/blob/master/INSTALL.rst After installing LuaJIT2 development packages, this command installs the Lupa library using the Python package installer `pip` on Debian or Ubuntu. ```Shell pip install lupa ``` -------------------------------- ### Install pkg-config via Homebrew on OS X Source: https://github.com/scoder/lupa/blob/master/INSTALL.rst Command to install `pkg-config`, a helper tool for compiling applications, using Homebrew on macOS. This is often required for Lupa's `setup.py` to find Lua libraries. ```Shell brew install pkg-config ``` -------------------------------- ### Install LuaJIT2 development package on Debian/Ubuntu Source: https://github.com/scoder/lupa/blob/master/INSTALL.rst Command to install the LuaJIT2 development headers and libraries on Debian or Ubuntu systems, a prerequisite for installing Lupa with LuaJIT2. ```Shell apt-get install libluajit-5.1-dev ``` -------------------------------- ### Install Lupa via pip after Homebrew Lua/pkg-config setup (OS X) Source: https://github.com/scoder/lupa/blob/master/INSTALL.rst After installing Lua and `pkg-config` via Homebrew, this command installs the Lupa library using the Python package installer `pip` on macOS. ```Shell pip install lupa ``` -------------------------------- ### Install Lua via Homebrew on OS X Source: https://github.com/scoder/lupa/blob/master/INSTALL.rst Command to install the Lua runtime using Homebrew on macOS. This is a prerequisite for installing Lupa with standard Lua on macOS. ```Shell brew install lua ``` -------------------------------- ### Lupa Build Configuration Options Reference Source: https://github.com/scoder/lupa/blob/master/README.rst Documentation for command-line options available during `lupa` setup to control which Lua version is used for building. These options allow specifying custom Lua library and include paths, or forcing the use of bundled or external Lua versions. ```APIDOC --lua-lib Description: Specifies the Lua library file path. Example: --lua-lib /usr/local/lib/lualib.a --lua-includes Description: Specifies the Lua include directory. Example: --lua-includes /usr/local/include --use-bundle Description: Forces the build to use the bundled LuaJIT or Lua version instead of searching for an installed one. --no-bundle Description: Prevents the use of the bundled LuaJIT/Lua, forcing a search for an installed version (e.g., via pkg-config). --no-lua-jit Description: Disables the use or search for LuaJIT, ensuring only Lua is considered for the build. ``` -------------------------------- ### Install Lua 5.2 development package on Debian/Ubuntu Source: https://github.com/scoder/lupa/blob/master/INSTALL.rst Command to install the necessary Lua 5.2 development headers and libraries on Debian or Ubuntu systems, a prerequisite for installing Lupa with Lua 5.2. ```Shell apt-get install liblua5.2-dev ``` -------------------------------- ### Python: Check Lupa LuaRuntime Memory Usage Source: https://github.com/scoder/lupa/blob/master/README.rst This example demonstrates how to initialize a `lupa.LuaRuntime` instance with an unlimited memory setting and then query its memory usage. It shows the difference between memory used by user code and total memory including the runtime's overhead. ```python from lupa import lua52 lua = lua52.LuaRuntime(max_memory=0) # 0 for unlimited, default is None lua.get_memory_used() # memory used by your code # Expected output: 0 total_lua_memory = lua.get_memory_used(total=True) # includes memory used by the runtime itself assert total_lua_memory > 0 # exact amount depends on your lua version and other factors ``` -------------------------------- ### Python: Configure dlopen Flags for Lua Binary Modules in Lupa Source: https://github.com/scoder/lupa/blob/master/README.rst This example demonstrates how to manually set `sys.setdlopenflags` to enable global symbol visibility, which is often required for `lupa` to load Lua binary modules correctly. It shows how to save and restore original flags and then import `lupa`. ```python import sys orig_dlflags = sys.getdlopenflags() sys.setdlopenflags(258) import lupa sys.setdlopenflags(orig_dlflags) lua = lupa.LuaRuntime() posix_module = lua.require('posix') # doctest: +SKIP ``` -------------------------------- ### Basic Lua Runtime Initialization and Evaluation Source: https://github.com/scoder/lupa/blob/master/README.rst This example initializes a Lua runtime instance from `lupa.lua54` with the `unpack_returned_tuples=True` flag enabled. It demonstrates evaluating a simple Lua expression (`1+1`), defining a Lua function, and calling it while passing a Python function as an argument. The snippet also shows how to execute Python code and access Python built-ins directly from within Lua using `python.eval` and `python.builtins`. ```python >>> from lupa.lua54 import LuaRuntime >>> lua = LuaRuntime(unpack_returned_tuples=True) >>> lua.eval('1+1') 2 >>> lua_func = lua.eval('function(f, n) return f(n) end') >>> def py_add1(n): return n+1 >>> lua_func(py_add1, 2) 3 >>> lua.eval('python.eval(" 2 ** 2 ")') == 4 True >>> lua.eval('python.builtins.str(4)') == '4' True ``` -------------------------------- ### Set ARCHFLAGS for 64-bit MacOS-X builds Source: https://github.com/scoder/lupa/blob/master/INSTALL.rst Environment variable setting required on 64-bit MacOS-X to ensure that both LuaJIT and Lupa are built for the correct architecture (x86_64) and to prevent fat binary generation issues. ```Shell export ARCHFLAGS="-arch x86_64" ``` -------------------------------- ### Interacting with Lua-Created Coroutines in Python Source: https://github.com/scoder/lupa/blob/master/README.rst This example demonstrates how to create Lua coroutines directly within Lua code using `coroutine.create()` and then pass them back to Python. It shows how to resume a Lua coroutine from Lua, and how Python can then interact with both running and uninitialized Lua coroutines as Python generators, as well as creating new coroutines from the original Lua function. ```python lua_code = '''\ function f(N) for i=0,N do coroutine.yield( i%2 ) end end ; co1 = coroutine.create(f) ; co2 = coroutine.create(f) ; status, first_result = coroutine.resume(co2, 2) ; -- starting! return f, co1, co2, status, first_result ''' lua = LuaRuntime() f, co, lua_gen, status, first_result = lua.execute(lua_code) # a running coroutine: status True first_result 0 list(lua_gen) [1, 0] list(lua_gen) [] # an uninitialised coroutine: gen = co(4) list(enumerate(gen)) [(0, 0), (1, 1), (2, 0), (3, 1), (4, 0)] gen = co(2) list(enumerate(gen)) [(0, 0), (1, 1), (2, 0)] # a plain function: gen = f.coroutine(4) list(enumerate(gen)) [(0, 0), (1, 1), (2, 0), (3, 1), (4, 0)] ``` -------------------------------- ### Python Integration of Lua Coroutine Yielding Source: https://github.com/scoder/lupa/blob/master/README.rst This example demonstrates how to define a Lua function that yields values using `coroutine.yield`, evaluate it in Python using `LuaRuntime`, and then interact with the resulting Lua coroutine as if it were a Python generator. It shows how to create a coroutine from a Lua function and iterate over its yielded values. ```python lua_code = '''\ function(N) for i=0,N do coroutine.yield( i%2 ) end end ''' lua = LuaRuntime() f = lua.eval(lua_code) gen = f.coroutine(4) list(enumerate(gen)) ``` -------------------------------- ### Parallel Mandelbrot Image Generation using Lupa and Python Threading Source: https://github.com/scoder/lupa/blob/master/README.rst This example demonstrates how to use the Lupa library to execute Lua code in parallel from Python. It calculates a Mandelbrot set, distributing the workload across multiple Lua runtimes, each managed by a Python thread. The results are then combined and displayed as an image using Pillow. ```Lua function mandelbrot_line(image_size, line_number, thread_count) local result = "" local buf = {} local p = 0 local ba = 256 local bb = 2 local x0 = -2.0 local y0 = -1.5 local x_step = 3.0 / image_size local y_step = 3.0 / image_size for y_idx = line_number, image_size, thread_count do local y = y0 + y_idx * y_step local b = 1 for x_idx = 1, image_size do local x = x0 + x_idx * x_step local Zr = 0.0 local Zi = 0.0 local Zrq = 0.0 local Ziq = 0.0 for i = 1, 256 do Zi = 2.0 * Zr * Zi + y Zr = Zrq - Ziq + x Ziq = Zi*Zi Zrq = Zr*Zr if Zrq+Ziq > 4.0 then b = b + 1; break; end end if b >= 256 then p = p + 1; buf[p] = 511 - b; b = 1; end end if b ~= 1 then p = p + 1; buf[p] = (ba-b)*bb; end result = result .. char(unpack(buf, 1, p)) end return result end ``` ```Python image_size = 1280 # == 1280 x 1280 thread_count = 8 from lupa import LuaRuntime lua_funcs = [ LuaRuntime(encoding=None).eval(lua_code) for _ in range(thread_count) ] results = [None] * thread_count def mandelbrot(i, lua_func): results[i] = lua_func(image_size, i+1, thread_count) import threading threads = [ threading.Thread(target=mandelbrot, args=(i,lua_func)) for i, lua_func in enumerate(lua_funcs) ] for thread in threads: thread.start() for thread in threads: thread.join() result_buffer = b''.join(results) # use Pillow to display the image from PIL import Image image = Image.frombytes('1', (image_size, image_size), result_buffer) image.show() ``` -------------------------------- ### Iterate Over Python Lists in Lua with python.iter() Source: https://github.com/scoder/lupa/blob/master/README.rst Provides a Lua function that demonstrates how to iterate over a plain Python iterable (like a list) using `python.iter()`. The example shows copying items from a Python list into a Lua table. ```python >>> lua_copy = lua.eval(''' ... function(L) ... local t, i = {}, 1 ... for item in python.iter(L) do ... t[i] = item ... i = i + 1 ... end ... return t ... end ... ''') >>> table = lua_copy([1,2,3,4]) >>> len(table) 4 >>> table[1] # Lua indexing 1 ``` ```lua function(L) local t, i = {}, 1 for item in python.iter(L) do t[i] = item i = i + 1 end return t end ``` -------------------------------- ### Unpacking Python Tuples in Lua with `unpack_returned_tuples` Source: https://github.com/scoder/lupa/blob/master/README.rst This example highlights the effect of the `unpack_returned_tuples=True` flag when initializing a `LuaRuntime`. When enabled, Python tuples returned to Lua are automatically unpacked into multiple Lua values. This allows for direct assignment to multiple Lua variables, as demonstrated by accessing the unpacked values from the Lua global environment. ```python >>> lua.execute('a,b,c = python.eval("(1,2)")') >>> g = lua.globals() >>> g.a 1 >>> g.b 2 >>> g.c is None ``` -------------------------------- ### Fine-Grained Python Object Attribute Control with Custom Getters and Setters Source: https://github.com/scoder/lupa/blob/master/README.rst This example demonstrates using `attribute_handlers` (a tuple of custom getter and setter functions) to precisely control how Lua code interacts with Python object attributes. It allows for specific read/write permissions on a per-attribute basis, providing more granular control than a single filter function. ```Python def getter(obj, attr_name): if attr_name == 'yes': return getattr(obj, attr_name) raise AttributeError( 'not allowed to read attribute "%s"' % attr_name) def setter(obj, attr_name, value): if attr_name == 'put': setattr(obj, attr_name, value) return raise AttributeError( 'not allowed to write attribute "%s"' % attr_name) class X: yes = 123 put = 'abc' noway = 2.1 x = X() lua = lupa.LuaRuntime(attribute_handlers=(getter, setter)) func = lua.eval('function(x) return x.yes end') func(x) # getting 'yes' func = lua.eval('function(x) x.put = "ABC"; end') func(x) # setting 'put' print(x.put) func = lua.eval('function(x) x.noway = 42; end') func(x) # setting 'noway' ``` -------------------------------- ### Controlling Python Object Attribute Access from Lua using `attribute_filter` Source: https://github.com/scoder/lupa/blob/master/README.rst This snippet illustrates how to implement a custom `attribute_filter` function when initializing a `LuaRuntime`. This filter intercepts all attribute access attempts from Lua to Python objects, allowing developers to whitelist or blacklist attributes (e.g., preventing access to private attributes starting with '_'). ```Python def filter_attribute_access(obj, attr_name, is_setting): if isinstance(attr_name, unicode): if not attr_name.startswith('_'): return attr_name raise AttributeError('access denied') lua = lupa.LuaRuntime( register_eval=False, attribute_filter=filter_attribute_access) func = lua.eval('function(x) return x.__class__ end') func(lua) ``` -------------------------------- ### Passing Values to Lua Coroutines from Python Source: https://github.com/scoder/lupa/blob/master/README.rst This snippet illustrates how to send values into a Lua coroutine from Python using the `.send()` method. The Lua function is designed to receive values via `coroutine.yield()` and store them. The Python code initializes the coroutine, sends an initial `None` to start it, then sends multiple integer values, and finally sends `None` again to signal termination and retrieve the collected results. ```python lua_code = '''\ function() local t,i = {},0 local value = coroutine.yield() while value do t[i] = value i = i + 1 value = coroutine.yield() end return t end ''' f = lua.eval(lua_code) co = f.coroutine() # create coroutine co.send(None) # start coroutine (stops at first yield) for i in range(3): co.send(i*2) mapping = co.send(None) # loop termination signal sorted(mapping.items()) ``` -------------------------------- ### luac Command-Line Synopsis Source: https://github.com/scoder/lupa/blob/master/third-party/lua51/doc/luac.html Describes the basic command-line syntax for invoking the luac compiler, showing optional arguments and filenames. This outlines how to execute the luac utility from a shell. ```APIDOC luac: Synopsis: luac [options] [filenames] Usage Notes: - '-' can be used to indicate standard input as a source file. - '--' signals the end of options, treating subsequent arguments as filenames. ``` -------------------------------- ### Creating Lua Tables with `lua.table()` Helper Source: https://github.com/scoder/lupa/blob/master/README.rst Demonstrates the `lua.table()` helper method provided by `LuaRuntime` to simplify the creation of Lua tables directly from Python. It shows how to pass both positional arguments (for array-like parts) and keyword arguments (for dictionary-like parts) to construct complex Lua tables. ```python t = lua.table(10, 20, 30, 40) lupa.lua_type(t) 'table' list(t) [1, 2, 3, 4] list(t.values()) [10, 20, 30, 40] t = lua.table(10, 20, 30, 40, a=1, b=2) t[3] 30 t['b'] 2 ``` -------------------------------- ### Lua Interpreter Command-Line Synopsis Source: https://github.com/scoder/lupa/blob/master/third-party/lua51/doc/lua.html This snippet illustrates the fundamental structure for running the Lua interpreter from the command line. It shows how to specify optional flags, a Lua script file, and arguments to be passed to the script. ```APIDOC lua [ options ] [ script [ args ] ] ``` -------------------------------- ### Lupa LuaRuntime Memory Management API Reference Source: https://github.com/scoder/lupa/blob/master/README.rst Documentation for `lupa.LuaRuntime` methods related to memory management, including functions to query current memory usage, retrieve or set memory limits, and the `LuaMemoryError` exception. ```APIDOC get_memory_used(total: bool = False) Description: Get the current memory usage of the LuaRuntime. Parameters: total: If True, includes memory used by the LuaRuntime itself. Defaults to False. Returns: int: The current memory usage in bytes. get_max_memory(total: bool = False) Description: Get the current memory limit of the LuaRuntime. Parameters: total: If True, considers the total memory limit including runtime overhead. Defaults to False. Returns: int: The current memory limit in bytes. 0 means no memory limitation. set_max_memory(max_memory: int, total: bool = False) Description: Change the memory limit of the LuaRuntime. Parameters: max_memory: The new memory limit in bytes. Values below or equal to 0 mean no limit. total: If True, sets the total memory limit including runtime overhead. Defaults to False. LuaMemoryError Description: Exception raised when Lua code hits the memory limit. Inherits: LuaError, MemoryError ``` -------------------------------- ### Create Lua Table from Python Data with lua.table_from Source: https://github.com/scoder/lupa/blob/master/README.rst Demonstrates the basic usage of `lua.table_from` to construct a Lua table from a mix of Python lists, tuples, and dictionaries. It shows how keys are overwritten when present in multiple input mappings and how to access elements. ```python >>> t = lua.table_from([10, 20, 30], {'a': 11, 'b': 22}, (40, 50), {'b': 42}) >>> t['a'] 11 >>> t['b'] 42 >>> t[5] 50 >>> sorted(t.values()) [10, 11, 20, 30, 40, 42, 50] ``` -------------------------------- ### LuaRuntime Memory Management API Source: https://github.com/scoder/lupa/blob/master/README.rst Documentation for the `LuaRuntime` class methods related to memory usage control. It details how to set a maximum memory limit during initialization and provides methods to query and dynamically adjust the memory limit of a Lua runtime instance. ```APIDOC LuaRuntime: __init__(max_memory: int = 0, ...) max_memory: The maximum memory in bytes that the Lua runtime is allowed to use. A value of 0 (default) means no memory limit is enforced. get_memory_usage() -> int Returns the current memory usage of the Lua runtime in bytes. get_memory_limit() -> int Returns the configured memory limit for the Lua runtime in bytes. set_memory_limit(limit: int) Sets a new memory limit for the Lua runtime in bytes. ``` -------------------------------- ### Lupa's Basic `None` to `nil` Mapping Source: https://github.com/scoder/lupa/blob/master/README.rst Illustrates Lupa's direct mapping of Python's `None` to Lua's `nil` and vice-versa for simple evaluations and function calls, showing that they are generally treated as equivalent for 'no value' semantics. ```python lua.eval('nil') is None True is_nil = lua.eval('function(x) return x == nil end') is_nil(None) True ``` -------------------------------- ### Accessing and Converting Lua Tables from Python Source: https://github.com/scoder/lupa/blob/master/README.rst Illustrates how Lua tables are accessed and behave when exposed to Python. It covers 1-based indexing for array-like tables, dictionary-like access for tables with arbitrary keys, and conversion methods like `list()` and `dict()` to transform Lua tables into Python data structures. ```python table = lua.eval('{10,20,30,40}') table[1] 10 table[4] 40 list(table) [1, 2, 3, 4] dict(table) {1: 10, 2: 20, 3: 30, 4: 40} list(table.values()) [10, 20, 30, 40] len(table) 4 mapping = lua.eval('{ [1] = -1 }') list(mapping) [1] mapping = lua.eval('{ [20] = -20; [3] = -3 }') mapping[20] -20 mapping[3] -3 sorted(mapping.values()) [-20, -3] sorted(mapping.items()) [(3, -3), (20, -20)] mapping[-3] = 3 # -3 used as key, not index! mapping[-3] 3 sorted(mapping) [-3, 3, 20] sorted(mapping.items()) [(-3, 3), (3, -3), (20, -20)] ``` -------------------------------- ### Calling Python Functions and Methods from Lua Source: https://github.com/scoder/lupa/blob/master/README.rst Illustrates how to expose Python functions and class methods to Lua scripts. It demonstrates defining a Python function and a class with a method, then using `lua.eval` to create Lua functions that can invoke these Python callables, passing arguments and receiving return values. ```python def add_one(num): return num + 1 >>> lua_func = lua.eval('function(num, py_func) return py_func(num) end') >>> lua_func(48, add_one) 49 >>> class MyClass(): ... def my_method(self): ... return 345 >>> obj = MyClass() >>> lua_func = lua.eval('function(py_obj) return py_obj:my_method() end') >>> lua_func(obj) 345 ``` -------------------------------- ### Lua Interpreter Command-Line Options Source: https://github.com/scoder/lupa/blob/master/third-party/lua51/doc/lua.html This section provides a detailed reference for all available command-line options for the Lua interpreter. Each option is described with its purpose and how it modifies the interpreter's behavior, such as executing statements, entering interactive mode, or loading libraries. ```APIDOC -: load and execute the standard input as a file, that is, not interactively, even when the standard input is a terminal. -e stat: execute statement stat. You need to quote stat if it contains spaces, quotes, or other characters special to the shell. -i: enter interactive mode after script is executed. -l name: call require('name') before executing script. Typically used to load libraries. -v: show version information. ``` -------------------------------- ### LuaRuntime.table_from() Helper Method Source: https://github.com/scoder/lupa/blob/master/CHANGES.rst Provides a convenient way to create Lua tables directly from Python mappings (dictionaries) or sequences (lists, tuples), simplifying data exchange between Python and Lua. ```APIDOC LuaRuntime.table_from(*args: Union[Mapping, Sequence]) -> LuaTable ``` -------------------------------- ### Enhanced eval() and execute() with Positional Arguments Source: https://github.com/scoder/lupa/blob/master/CHANGES.rst The `eval()` and `execute()` methods now support optional positional arguments, allowing for more flexible data passing into the Lua execution context. ```APIDOC eval(lua_code: str, *args) execute(lua_code: str, *args) ``` -------------------------------- ### Global Lua Functions and Variables Source: https://github.com/scoder/lupa/blob/master/third-party/lua51/doc/contents.html This section lists the standard global functions and variables accessible directly in the Lua environment, covering basic operations, environment manipulation, and type conversions. ```APIDOC _G _VERSION assert collectgarbage dofile error getfenv getmetatable ipairs load loadfile loadstring module next pairs pcall print rawequal rawget rawset require select setfenv setmetatable tonumber tostring type unpack xpcall ``` -------------------------------- ### Python: Triggering and Handling Lupa LuaMemoryError Source: https://github.com/scoder/lupa/blob/master/README.rst This snippet illustrates how to set a strict memory limit on a `lupa.LuaRuntime` instance and then execute Lua code that exceeds this limit, leading to a `lupa.LuaMemoryError`. It demonstrates the exception behavior when memory constraints are violated. ```python lua.set_max_memory(100) lua.eval("string.rep('a', 1000)") # doctest: +IGNORE_EXCEPTION_DETAIL # Expected output (Traceback): # Traceback (most recent call last): # ... # lupa.LuaMemoryError: not enough memory ``` -------------------------------- ### Lua C API Types and Functions Reference Source: https://github.com/scoder/lupa/blob/master/third-party/lua51/doc/contents.html This section provides a comprehensive reference for the Lua C API, listing all available types and functions for direct interaction with the Lua state from C code. It includes fundamental data types, callback function types, debugging structures, and a wide array of functions for stack manipulation, value conversion, table operations, function calls, and state management. ```APIDOC C API Types: lua_Alloc lua_CFunction lua_Debug lua_Hook lua_Integer lua_Number lua_Reader lua_State lua_Writer C API Functions: lua_atpanic lua_call lua_checkstack lua_close lua_concat lua_cpcall lua_createtable lua_dump lua_equal lua_error lua_gc lua_getallocf lua_getfenv lua_getfield lua_getglobal lua_gethook lua_gethookcount lua_gethookmask lua_getinfo lua_getlocal lua_getmetatable lua_getstack lua_gettable lua_gettop lua_getupvalue lua_insert lua_isboolean lua_iscfunction lua_isfunction lua_islightuserdata lua_isnil lua_isnone lua_isnoneornil lua_isnumber lua_isstring lua_istable lua_isthread lua_isuserdata lua_lessthan lua_load lua_newstate lua_newtable lua_newthread lua_newuserdata lua_next lua_objlen lua_pcall lua_pop lua_pushboolean lua_pushcclosure lua_pushcfunction lua_pushfstring lua_pushinteger lua_pushlightuserdata lua_pushliteral lua_pushlstring lua_pushnil lua_pushnumber lua_pushstring lua_pushthread lua_pushvalue lua_pushvfstring lua_rawequal lua_rawget lua_rawgeti lua_rawset lua_rawseti lua_register lua_remove lua_replace lua_resume lua_setallocf lua_setfenv lua_setfield lua_setglobal lua_sethook lua_setlocal lua_setmetatable lua_settable lua_settop lua_setupvalue lua_status lua_toboolean lua_tocfunction lua_tointeger lua_tolstring lua_tonumber lua_topointer lua_tostring lua_tothread lua_touserdata lua_type lua_typename lua_upvalueindex lua_xmove lua_yield ``` -------------------------------- ### luac Command-Line Options Reference Source: https://github.com/scoder/lupa/blob/master/third-party/lua51/doc/luac.html A comprehensive reference of all command-line options supported by the luac compiler, detailing their function and impact on the compilation process. Each option modifies luac's behavior regarding output, debugging, or integrity checks. ```APIDOC luac Options: -l: Description: Produce a listing of the compiled bytecode for Lua's virtual machine. If no files are given, luac loads luac.out and lists its contents. -o file: Description: Output to 'file', instead of the default 'luac.out'. Using '-' for 'file' directs output to standard output (platform-dependent). The output file may be a source file, so caution is advised to avoid overwriting. -p: Description: Load files but do not generate any output file. Primarily used for syntax checking and testing precompiled chunks. Corrupted files will likely generate errors upon loading. No messages are displayed if the file passes the integrity test. -s: Description: Strip debug information (like line numbers and local variable names) before writing the output file. This saves space in large chunks but can reduce the detail in error messages if issues occur during runtime. -v: Description: Show version information for the luac compiler. ``` -------------------------------- ### Lua Auxiliary Library (luaL) Functions and Types Overview Source: https://github.com/scoder/lupa/blob/master/third-party/lua51/doc/contents.html A structured list of the core functions and types provided by the Lua auxiliary library (luaL). These elements are fundamental for developing robust Lua extensions and interacting with the Lua runtime environment from C. ```APIDOC Auxiliary Library Types: luaL_Buffer luaL_Reg Auxiliary Library Functions: luaL_addchar luaL_addlstring luaL_addsize luaL_addstring luaL_addvalue luaL_argcheck luaL_argerror luaL_buffinit luaL_callmeta luaL_checkany luaL_checkint luaL_checkinteger luaL_checklong luaL_checklstring luaL_checknumber luaL_checkoption luaL_checkstack luaL_checkstring luaL_checktype luaL_checkudata luaL_dofile luaL_dostring luaL_error luaL_getmetafield luaL_getmetatable luaL_gsub luaL_loadbuffer luaL_loadfile luaL_loadstring luaL_newmetatable luaL_newstate luaL_openlibs luaL_optint luaL_optinteger luaL_optlong luaL_optlstring luaL_optnumber luaL_optstring luaL_prepbuffer luaL_pushresult luaL_ref luaL_register luaL_typename luaL_typerror luaL_unref luaL_where ``` -------------------------------- ### Importing Specific Lua Versions with Lupa Source: https://github.com/scoder/lupa/blob/master/README.rst This Python code demonstrates how to explicitly import a specific Lua version (LuaJIT 2.1, Lua 5.4, Lua 5.3) from Lupa, or gracefully fall back to the default Lupa import if specific versions are unavailable. After importing, it prints the active Lua implementation and its compiled version, which is useful for verifying the runtime environment. ```python try: import lupa.luajit21 as lupa except ImportError: try: import lupa.lua54 as lupa except ImportError: try: import lupa.lua53 as lupa except ImportError: import lupa print(f"Using {lupa.LuaRuntime().lua_implementation} (compiled with {lupa.LUA_VERSION})") ``` -------------------------------- ### Lua Math Library Functions Source: https://github.com/scoder/lupa/blob/master/third-party/lua51/doc/contents.html Mathematical functions and constants provided by Lua's `math` library, covering trigonometry, logarithms, exponentiation, and number manipulation. ```APIDOC math.abs math.acos math.asin math.atan math.atan2 math.ceil math.cos math.cosh math.deg math.exp math.floor math.fmod math.frexp math.huge math.ldexp math.log math.log10 math.max math.min math.modf math.pi math.pow math.rad math.random math.randomseed math.sin math.sinh math.sqrt math.tan math.tanh ``` -------------------------------- ### lupa.unpacks_lua_table and lupa.unpacks_lua_table_method Decorators Source: https://github.com/scoder/lupa/blob/master/CHANGES.rst These decorators facilitate calling Python functions and methods from Lua using named arguments, by automatically unpacking Lua table arguments into Python keyword arguments. ```APIDOC @lupa.unpacks_lua_table def python_function_from_lua(arg1, arg2, ...): ... @lupa.unpacks_lua_table_method def python_method_from_lua(self, arg1, arg2, ...): ... ``` -------------------------------- ### Lua Package Library Functions and Variables Source: https://github.com/scoder/lupa/blob/master/third-party/lua51/doc/contents.html Functions and variables within Lua's `package` library, used for managing modules and controlling the module loading process, including paths and loaded modules. ```APIDOC package.cpath package.loaded package.loaders package.loadlib package.path package.preload ``` -------------------------------- ### Lua IO Library Functions Source: https://github.com/scoder/lupa/blob/master/third-party/lua51/doc/contents.html Functions in Lua's `io` library for general input/output operations, including file handling, standard streams (stdin, stdout, stderr), and temporary file creation. ```APIDOC io.close io.flush io.input io.lines io.open io.output io.popen io.read io.stderr io.stdin io.stdout io.tmpfile io.type io.write ``` -------------------------------- ### Manually Wrap Python Callables for Lua Named Arguments Source: https://github.com/scoder/lupa/blob/master/README.rst Demonstrates how to manually wrap an existing Python callable (like `operator.add`) with `lupa.unpacks_lua_table` when you don't control the function's definition. This allows the wrapped callable to accept named arguments from Lua, enabling flexible integration without modifying the original function. ```python import operator >>> wrapped_py_add = lupa.unpacks_lua_table(operator.add) >>> lua_func = lua.eval('function(a, b, py_func) return py_func{a, b} end') >>> lua_func(5, 6, wrapped_py_add) 11 ``` -------------------------------- ### Lupa 1.0 Breaking API Changes and Behavioral Updates Source: https://github.com/scoder/lupa/blob/master/CHANGES.rst This section details significant backwards-incompatible changes introduced in Lupa 1.0, aimed at aligning Python-Lua interaction more closely with idiomatic Lua practices. Key changes include `None` to `nil` mapping, enhanced tuple unpacking during iteration, and corrected handling of bound Python method calls from Lua. ```APIDOC 1. None to nil Mapping: - Python `None` return values are now mapped to Lua `nil`. - Exception: During iteration, the *first* returned value must not be `nil` in Lua. If the first item in an exploded tuple or an iterator's return is `None`, it is mapped to `python.none`. - Subsequent `None` values in the same iteration are mapped to `nil`. 2. Iteration with unpack_returned_tuples=True: - Iteration now unpacks tuple values, including `enumerate()` iteration, which yields a flat sequence of counter and unpacked values. 3. Calling Bound Python Methods from Lua: - When calling bound Python methods from Lua using the colon syntax (e.g., `obj:meth()`), Lupa now prevents Python from prepending the `self` argument a second time. - The Python method is now correctly called as `obj.meth()`, resolving issues with redundant `self` arguments. ``` -------------------------------- ### Lua File Object Methods Source: https://github.com/scoder/lupa/blob/master/third-party/lua51/doc/contents.html Methods available on Lua file objects, returned by functions like `io.open`, for performing operations such as closing, flushing, reading, and writing to files. ```APIDOC file:close file:flush file:lines file:read file:seek file:setvbuf file:write ``` -------------------------------- ### LuaRuntime.compile() Method Source: https://github.com/scoder/lupa/blob/master/CHANGES.rst Introduces a new method on the LuaRuntime object to compile Lua code without immediate execution. This allows for pre-compilation and potential performance benefits or syntax validation. ```APIDOC LuaRuntime.compile(code: str) -> LuaFunction ``` -------------------------------- ### Recursive Lua Table Creation with lua.table_from(recursive=True) Source: https://github.com/scoder/lupa/blob/master/README.rst Illustrates how to use the `recursive=True` argument with `lua.table_from` (available since Lupa 2.1) to recursively map nested Python data structures into corresponding Lua tables, preserving their hierarchical relationships. ```python >>> t = lua.table_from( ... [ ... # t1: ... [ ... [10, 20, 30], ... {'a': 11, 'b': 22} ... ], ... # t2: ... [ ... (40, 50), ... {'b': 42} ... ] ... ], ... recursive=True ... ) >>> t1, t2 = t.values() >>> list(t1[1].values()) [10, 20, 30] >>> t1[2]['a'] 11 >>> t1[2]['b'] 22 >>> t2[2]['b'] 42 >>> list(t1[1].values()) [10, 20, 30] >>> list(t2[1].values()) [40, 50] ``` -------------------------------- ### Handle Non-Existent Keys in Lua Tables (Python None) Source: https://github.com/scoder/lupa/blob/master/README.rst Explains that attempting to access non-existent keys or indices in a Lua table from Python using Lupa will return `None`, mirroring Lua's `nil` behavior. This is similar to Python dictionary's `.get()` method. ```python >>> table = lua.table(10, 20, 30, 40) >>> table[1000000] is None True >>> table['no such key'] is None True >>> mapping = lua.eval('{ [20] = -20; [3] = -3 }') >>> mapping['no such key'] is None True ``` -------------------------------- ### Lua OS Library Functions Source: https://github.com/scoder/lupa/blob/master/third-party/lua51/doc/contents.html Functions in Lua's `os` library for interacting with the operating system, such as managing time, environment variables, executing commands, and file system operations. ```APIDOC os.clock os.date os.difftime os.execute os.exit os.getenv os.remove os.rename os.setlocale os.time os.tmpname ``` -------------------------------- ### Lupa's `None` Handling During Iteration Source: https://github.com/scoder/lupa/blob/master/README.rst Explains how Lupa special cases `None` values during iteration by replacing them with a constant `python.none` instead of `nil`. This is crucial because `nil` acts as a termination marker for Lua iterators, ensuring that `None` values are preserved when iterating over Python sequences from Lua. ```python _ = lua.require("table") func = lua.eval(''' function(items) local t = {} for value in python.iter(items) do table.insert(t, value == python.none) end return t end ''') items = [1, None ,2] list(func(items).values()) [False, True, False] ``` -------------------------------- ### Iterating Python Dictionaries in Lua with `iterex` Source: https://github.com/scoder/lupa/blob/master/README.rst Demonstrates how to iterate over a Python dictionary's items from Lua using `python.iterex`. This snippet shows how to copy Python dictionary contents into a Lua table, highlighting the need for `lupa.as_attrgetter` to access Python methods like `items()` from Lua. ```python lua_copy = lua.eval(''' function(d) local t = {} for key, value in python.iterex(d.items()) do t[key] = value end return t end ''') d = dict(a=1, b=2, c=3) table = lua_copy( lupa.as_attrgetter(d) ) table['b'] 2 ``` -------------------------------- ### Lua Debug Library Functions Source: https://github.com/scoder/lupa/blob/master/third-party/lua51/doc/contents.html An overview of functions in Lua's `debug` library, primarily used for debugging purposes such as inspecting call stacks, variables, and setting hooks. ```APIDOC debug.debug debug.getfenv debug.gethook debug.getinfo debug.getlocal debug.getmetatable debug.getregistry debug.getupvalue debug.setfenv debug.sethook debug.setlocal debug.setmetatable debug.setupvalue debug.traceback ``` -------------------------------- ### Lupa's `None` Handling in Tuple Unpacking Iteration Source: https://github.com/scoder/lupa/blob/master/README.rst Demonstrates Lupa's specific behavior when unpacking tuples during iteration. It shows that `python.none` replacement primarily applies to the first value in a tuple to prevent unintended iterator termination, while subsequent `None` values might map to `nil` if Lua doesn't inspect them for loop termination. ```python func = lua.eval(''' function(items) for a, b, c, d in python.iterex(items) do return {a == python.none, a == nil, --> a == python.none b == python.none, b == nil, --> b == nil c == python.none, c == nil, --> c == nil d == python.none, d == nil} --> d == nil ... end end ''') items = [(None, None, None, None)] list(func(items).values()) [True, False, False, True, False, True, False, True] items = [(None, None)] # note: no values for c/d => nil in Lua list(func(items).values()) [True, False, False, True, False, True, False, True] ``` -------------------------------- ### Identify Basic Python Object Types in Lua Source: https://github.com/scoder/lupa/blob/master/README.rst Illustrates how Lua's native `type()` function behaves when applied to wrapped Python numbers and strings. It shows that these basic types are converted to their corresponding Lua types. ```python >>> wrapped_type = lua.globals().type # Lua's own type() function >>> wrapped_type(1) == 'number' True >>> wrapped_type('abc') == 'string' True ``` -------------------------------- ### Access Lua Table Members via Python Attribute Syntax Source: https://github.com/scoder/lupa/blob/master/README.rst Shows that Lupa allows accessing Lua table members using Python's attribute syntax (e.g., `table.a`) in addition to the standard dictionary-like key access (`table['a']`). This feature is particularly useful for interacting with Lua library methods. ```python >>> table = lua.eval('{ a=1, b=2 }') >>> table.a, table.b (1, 2) >>> table.a == table['a'] True >>> string = lua.eval('string') # get the 'string' library table >>> print( string.lower('A') ) a ``` -------------------------------- ### Iterate Over Python Lists with Index in Lua using python.enumerate() Source: https://github.com/scoder/lupa/blob/master/README.rst Shows a simplified way to copy a Python list into a Lua table by iterating over it using `python.enumerate()`. This function provides both the index and the item during iteration, similar to Python's `enumerate()`. ```python >>> lua_copy = lua.eval(''' ... function(L) ... local t = {} ... for index, item in python.enumerate(L) do ... t[ index+1 ] = item ... end ... return t ... end ... ''') >>> table = lua_copy([1,2,3,4]) >>> len(table) 4 >>> table[1] # Lua indexing 1 ``` ```lua function(L) local t = {} for index, item in python.enumerate(L) do t[ index+1 ] = item end return t end ```