LuaJIT 學習(1)—— LuaJIT介紹

文章目錄

    • 介紹
    • Extensions Modules
      • `bit.*` — Bitwise operations
      • `ffi.*` — FFI library
      • `jit.*` — JIT compiler control
      • C API extensions
      • Profiler
    • Enhanced Standard Library Functions
      • `xpcall(f, err [,args...])` passes arguments
        • 例子: xpcall 的使用
      • `load*()` handle UTF-8 source code
        • 例子:變量名是中文
      • `load*()` add a mode parameter
      • `string.dump(f [,mode])` generates portable bytecode
      • `table.new(narray, nhash)` allocates a pre-sized table
        • 例子:table.new 的使用
      • `table.clear(tab)` clears a table
        • 例子:table.clear 的使用
      • Enhanced PRNG for `math.random()`
      • `io.*` functions handle 64 bit file offsets
      • `debug.*` functions identify metamethods
    • Fully Resumable VM
        • 例子:協程在 pcall 中 yield
        • 例子:協程在迭代器中 yield
    • Extensions from Lua 5.2
        • 例子:goto 的使用
        • 例子:'\z'轉義字符的使用
        • 例子:package.loadlib 的使用
    • Extensions from Lua 5.3

介紹

LuaJIT is a Just-In-Time Compiler (JIT) for the Lua programming language. Lua is a powerful, dynamic and light-weight programming language. It may be embedded or used as a general-purpose, stand-alone language.

LuaJIT is fully upwards-compatible with Lua 5.1. It supports all standard Lua library functions and the full set of Lua/C API functions.

LuaJIT is also fully ABI-compatible to Lua 5.1 at the linker/dynamic loader level. This means you can compile a C module against the standard Lua headers and load the same shared library from either Lua or LuaJIT.

LuaJIT extends the standard Lua VM with new functionality and adds several extension modules. Please note, this page is only about functional enhancements and not about performance enhancements, such as the optimized VM, the faster interpreter or the JIT compiler.

Extensions Modules

LuaJIT comes with several built-in extension modules:

bit.* — Bitwise operations

LuaJIT supports all bitwise operations as defined by Lua BitOp:

bit.tobit  bit.tohex  bit.bnot    bit.band bit.bor  bit.bxor
bit.lshift bit.rshift bit.arshift bit.rol  bit.ror  bit.bswap

This module is a LuaJIT built-in — you don’t need to download or install Lua BitOp. The Lua BitOp site has full documentation for all Lua BitOp API functions. The FFI adds support for 64 bit bitwise operations, using the same API functions.

Please make sure to require the module before using any of its functions:

local bit = require("bit")

An already installed Lua BitOp module is ignored by LuaJIT. This way you can use bit operations from both Lua and LuaJIT on a shared installation.

ffi.* — FFI library

The FFI library allows calling external C functions and the use of C data structures from pure Lua code【重點】.

jit.* — JIT compiler control

The functions in this module control the behavior of the JIT compiler engine.

C API extensions

LuaJIT adds some extra functions to the Lua/C API.

Profiler

LuaJIT has an integrated profiler.

Enhanced Standard Library Functions

xpcall(f, err [,args...]) passes arguments

Unlike the standard implementation in Lua 5.1, xpcall() passes any arguments after the error function to the function which is called in a protected context.

例子: xpcall 的使用
local function divide(a, b)if b == 0 thenerror("Division by zero")endreturn a / b
endlocal function error_handler(err)return "Handled error: " .. err
endlocal function safe_divide(a, b)local status, result = xpcall(divide, error_handler, a, b)if status thenreturn resultelseprint("Custom Error Handler: " .. result)  -- 自定義錯誤處理return nilend
endprint(safe_divide(10, 2))  -- 輸出:5
print(safe_divide(10, 0))  -- 輸出:Custom Error Handler: Handled error: Division by zero

load*() handle UTF-8 source code

Non-ASCII characters are handled transparently by the Lua source code parser. This allows the use of UTF-8 characters in identifiers and strings. A UTF-8 BOM is skipped at the start of the source code.

例子:變量名是中文
local 姓名 = "張三"
local 年齡 = 25print("姓名:" .. 姓名)
print("年齡:" .. 年齡)

使用標準的lua5.1會語法報錯

load*() add a mode parameter

As an extension from Lua 5.2, the functions loadstring(), loadfile() and (new) load() add an optional mode parameter.

The default mode string is "bt", which allows loading of both source code and bytecode. Use "t" to allow only source code or "b" to allow only bytecode to be loaded.

By default, the load* functions generate the native bytecode format. For cross-compilation purposes, add W to the mode string to force the 32 bit format and X to force the 64 bit format. Add both to force the opposite format. 【同時使用 WX 來強制使用與本機平臺相反的字節碼格式】Note that non-native bytecode generated by load* cannot be run, but can still be passed to string.dump.

string.dump(f [,mode]) generates portable bytecode

An extra argument has been added to string.dump(). If set to true or to a string which contains the character s, ‘stripped’ bytecode without debug information is generated. This speeds up later bytecode loading and reduces memory usage. See also the -b command line option.

The generated bytecode is portable and can be loaded on any architecture that LuaJIT supports. However, the bytecode compatibility versions must match. Bytecode only stays compatible within a major+minor version (x.y.aaa → x.y.bbb), except for development branches. Foreign bytecode (e.g. from Lua 5.1) is incompatible and cannot be loaded.

Note: LJ_GC64 mode requires a different frame layout, which implies a different, incompatible bytecode format between 32 bit and 64 bit ports. This may be rectified in the future. In the meantime, use the W and X modes of the load* functions for cross-compilation purposes.

Due to VM hardening, bytecode is not deterministic. Add d to the mode string to dump it in a deterministic manner: identical source code always gives a byte-for-byte identical bytecode dump. This feature is mainly useful for reproducible builds.

table.new(narray, nhash) allocates a pre-sized table

An extra library function table.new() can be made available via require("table.new"). This creates a pre-sized table, just like the C API equivalent lua_createtable(). This is useful for big tables if the final table size is known and automatic table resizing is too expensive.

例子:table.new 的使用
require("table.new")t = table.new(1,1)
t[1] = 1
t["a"] = 2
print(type(t)) -- table

table.clear(tab) clears a table

An extra library function table.clear() can be made available via require("table.clear"). This clears all keys and values from a table, but preserves the allocated array/hash sizes. This is useful when a table, which is linked from multiple places, needs to be cleared and/or when recycling a table for use by the same context. This avoids managing backlinks, saves an allocation and the overhead of incremental array/hash part growth.

Please note, this function is meant for very specific situations. In most cases it’s better to replace the (usually single) link with a new table and let the GC do its wo

例子:table.clear 的使用
local tab = {1, 2, 3, a = 10, b = 20}-- 清空表,但保留表的內存分配
require("table.clear")  -- 確保你加載了這個擴展函數
table.clear(tab)-- 現在 tab 變成了空表,但它的內存結構(數組和哈希大小)沒有改變
print(next(tab))  -- 輸出 nil,因為表已經沒有內容了

Enhanced PRNG for math.random()

LuaJIT uses a Tausworthe PRNG with period 2^223 to implement math.random() and math.randomseed(). The quality of the PRNG results is much superior compared to the standard Lua implementation, which uses the platform-specific ANSI rand().

The PRNG generates the same sequences from the same seeds on all platforms and makes use of all bits in the seed argument. math.random() without arguments generates 52 pseudo-random bits for every call. The result is uniformly distributed between 0.0 and 1.0. It’s correctly scaled up and rounded for math.random(n [,m]) to preserve uniformity.

Call math.randomseed() without any arguments to seed it from system entropy.

Important: Neither this nor any other PRNG based on the simplistic math.random() API is suitable for cryptographic use.

io.* functions handle 64 bit file offsets

The file I/O functions in the standard io.* library handle 64 bit file offsets. In particular, this means it’s possible to open files larger than 2 Gigabytes and to reposition or obtain the current file position for offsets beyond 2 GB (fp:seek() method).

debug.* functions identify metamethods

debug.getinfo() and lua_getinfo() also return information about invoked metamethods. The namewhat field is set to "metamethod" and the name field has the name of the corresponding metamethod (e.g. "__index").

Fully Resumable VM

The LuaJIT VM is fully resumable. This means you can yield from a coroutine even across contexts, where this would not possible with the standard Lua 5.1 VM: e.g. you can yield across pcall() and xpcall(), across iterators and across metamethods.

例子:協程在 pcall 中 yield
local function testCoroutine()pcall(function()print("Start coroutine")coroutine.yield() -- 在這里掛起協程print("Resumed coroutine")end)
endlocal co = coroutine.create(testCoroutine)coroutine.resume(co) -- 啟動協程
coroutine.resume(co) -- 恢復協程

輸出

Start coroutine
Resumed coroutine

而在標準的lua5.1中只輸出

Start coroutine
例子:協程在迭代器中 yield
local coroutine = require("coroutine")-- 一個自定義的迭代器,它會在每次返回一個元素時進行yield
function my_iterator(start, _end)local i = startreturn function()if i <= _end thencoroutine.yield()  -- 在返回每個元素時進行yieldi = i + 1return i - 1endend
end-- 創建一個協程來使用迭代器
local co = coroutine.create(function()for value in my_iterator(1, 5) doprint("迭代值: ", value)-- 在這里可以插入一些邏輯,例如,暫停協程,模擬某些異步操作end
end)-- 在主線程中控制協程的恢復
while coroutine.status(co) ~= "dead" doprint("恢復協程")coroutine.resume(co)-- 每次恢復時迭代器會繼續從`yield`的位置往下執行
end

輸出

恢復協程
恢復協程
迭代值:         1
恢復協程
迭代值:         2
恢復協程
迭代值:         3
恢復協程
迭代值:         4
恢復協程
迭代值:         5

而標準的lua5.1輸出

恢復協程

Extensions from Lua 5.2

LuaJIT supports some language and library extensions from Lua 5.2. Features that are unlikely to break existing code are unconditionally enabled:

  • goto and ::labels::.
例子:goto 的使用
local i = 0::start::  -- 標簽定義if i < 5 thenprint("i is " .. i)i = i + 1goto start  -- 跳回到 start 標簽
endprint("Finished")
  • Hex escapes '\x3F' and '\z' escape in strings.

The escape sequence ‘\z’ skips the following span of white-space characters, including line breaks; it is particularly useful to break and indent a long literal string into multiple lines without adding the newlines and spaces into the string contents.

例子:'\z’轉義字符的使用
local long_str ="This is a very long string that we\zwant to break into multiple lines,\zbut without including the newlines\zor spaces in the actual string content."print(long_str)

A byte in a literal string can also be specified by its numerical value. This can be done with the escape sequence \xXX, where XX is a sequence of exactly two hexadecimal digits, or with the escape sequence \ddd, where ddd is a sequence of up to three decimal digits. (Note that if a decimal escape is to be followed by a digit, it must be expressed using exactly three digits.) Strings in Lua can contain any 8-bit value, including embedded zeros, which can be specified as ‘\0’.

  • load(string|reader [, chunkname [,mode [,env]]]).
  • loadstring() is an alias for load().
  • loadfile(filename [,mode [,env]]).
  • math.log(x [,base]).
  • string.rep(s, n [,sep]).
  • string.format(): %q reversible. %s checks __tostring. %a and "%A added.
  • String matching pattern %g added.【%g: represents all printable characters except space.】
  • io.read("*L").【\*L”: reads the next line keeping the end of line (if present), returning nil on end of file.】
  • io.lines() and file:lines() process io.read() options.【和 io.read() 函數一樣的參數】
  • os.exit(status|true|false [,close]).
  • package.searchpath(name, path [, sep [, rep]]).
  • package.loadlib(name, "*").
例子:package.loadlib 的使用

假設你有兩個 C 庫:libcore.so 和 libext.so。libext.so 依賴于 libcore.so,但是你不想讓 libcore.so 的函數直接暴露到 Lua 環境中,而是只需要確保它的符號可以在 libext.so 中使用。

-- 僅僅加載 libcore.so,并確保符號鏈接到 Lua 環境中
package.loadlib("libcore.so", "*")-- 加載并使用 libext.so(它依賴于 libcore.so 的符號)
package.loadlib("libext.so", "luaopen_libext")
  • debug.getinfo() returns nparams and isvararg for option "u".
  • debug.getlocal() accepts function instead of level.
  • debug.getlocal() and debug.setlocal() accept negative indexes for varargs.
  • debug.getupvalue() and debug.setupvalue() handle C functions.
  • debug.upvalueid() and debug.upvaluejoin().
  • Lua/C API extensions: lua_version() lua_upvalueid() lua_upvaluejoin() lua_loadx() lua_copy() lua_tonumberx() lua_tointegerx() luaL_fileresult() luaL_execresult() luaL_loadfilex() luaL_loadbufferx() luaL_traceback() luaL_setfuncs() luaL_pushmodule() luaL_newlibtable() luaL_newlib() luaL_testudata() luaL_setmetatable()
  • Command line option -E.
  • Command line checks __tostring for errors.

Extensions from Lua 5.3

LuaJIT supports some extensions from Lua 5.3:

  • Unicode escape '\u{XX...}' embeds the UTF-8 encoding in string literals.【支持 Unicode 轉義!】
  • The argument table arg can be read (and modified) by LUA_INIT and -e chunks.
  • io.read() and file:read() accept formats with or without a leading *.
  • assert() accepts any type of error object.
  • table.move(a1, f, e, t [,a2]).

Moves elements from table a1 to table a2, performing the equivalent to the following multiple assignment: a2[t],··· = a1[f],···,a1[e]. The default for a2 is a1. The destination range can overlap with the source range. The number of elements to be moved must fit in a Lua integer.

Returns the destination table a2.

  • coroutine.isyieldable().

Returns 1 if the given coroutine can yield, and 0 otherwise.

  • Lua/C API extensions: lua_isyieldable()

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/897627.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/897627.shtml
英文地址,請注明出處:http://en.pswp.cn/news/897627.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

std::ranges::views::common, std::ranges::common_view

std::ranges::views::common, std::ranges::common_view C20 引入的用于將范圍適配為“通用范圍”的工具&#xff0c;主要解決某些算法需要傳統迭代器對&#xff08;如 begin 和 end 類型相同&#xff09;的問題。 基本概念 1. 功能 適配傳統算法&#xff1a;將范圍&#x…

4.3 數組和集合的初始及賦值

版權聲明&#xff1a;本文為博主原創文章&#xff0c;轉載請在顯著位置標明本文出處以及作者網名&#xff0c;未經作者允許不得用于商業目的 版權聲明&#xff1a;本文為博主原創文章&#xff0c;轉載請在顯著位置標明本文出處以及作者網名&#xff0c;未經作者允許不得用于商…

分布式光伏發電的發展現狀與前景

分布式光伏發電的發展現狀與前景 1、分布式光伏發電的背景2、分布式光伏發電的分類2.1、集中式光伏發電2.1.1、特點、原則2.1.2、優點2.1.3、缺點 2.2、分布式光伏發電2.2.1、特點、原則2.2.2、優點2.2.3、缺點 2.3、對比 3、分布式光伏發電的現狀4、分布式光伏發電的應用場景4…

13 | 實現統一的錯誤返回

提示&#xff1a; 所有體系課見專欄&#xff1a;Go 項目開發極速入門實戰課&#xff1b;歡迎加入 云原生 AI 實戰 星球&#xff0c;12 高質量體系課、20 高質量實戰項目助你在 AI 時代建立技術競爭力&#xff08;聚焦于 Go、云原生、AI Infra&#xff09;&#xff1b;本節課最終…

DeepSeek結合Mermaid繪圖(流程圖、時序圖、類圖、狀態圖、甘特圖、餅圖)轉載

思維速覽&#xff1a; 本文將詳細介紹如何利用DeepSeek結合Mermaid語法繪制各類專業圖表&#xff0c;幫助你提高工作效率和文檔質量。 ▍DeepSeek入門使用請看&#xff1a;deepseek保姆級入門教程&#xff08;網頁端使用 本地客戶端部署 使用技巧&#xff09; DeepSeek官網…

Java靜態變量與PHP靜態變量的對比

Java的靜態變量在多線程并發的情況下是線程共有的。以下是關鍵點總結&#xff1a; 存儲位置&#xff1a;靜態變量屬于類&#xff0c;存儲在方法區&#xff08;或元空間&#xff09;&#xff0c;這是所有線程共享的內存區域。因此&#xff0c;所有線程訪問的都是同一個靜態變量實…

c++20 Concepts的簡寫形式與requires 從句形式

c20 Concepts的簡寫形式與requires 從句形式 原始寫法&#xff08;簡寫形式&#xff09;等效寫法&#xff08;requires 從句形式&#xff09;關鍵區別說明&#xff1a;組合多個約束的示例&#xff1a;兩種形式的編譯結果&#xff1a;更復雜的約束示例&#xff1a;標準庫風格的約…

上下分層、左右分離的驅動設計思想

之前了解了最簡單的驅動程序、但是不易擴展、現在繼續學習、上下分層、左右分離的驅動設計思想。 1、led_dev.c函數 上層函數&#xff0c;①定義一個結構體&#xff0c;存儲函數用來接應app的函數。②定義一個入口函數&#xff0c;將我們接應的函數告訴內核&#xff0c;給這個…

人工智能在醫療領域的應用:技術革新與未來展望

人工智能&#xff08;AI&#xff09;技術正在重塑醫療行業的面貌。從輔助診斷到藥物研發&#xff0c;從健康管理到手術機器人&#xff0c;AI的廣泛應用不僅提升了醫療效率&#xff0c;還為精準醫療和個性化治療提供了新可能。根據2025年多份研究報告及政策文件&#xff0c;全球…

《歷史代碼分析》5、動態控制列表的列

?? 本系列《歷史代碼分析》為工作中遇到具有代表性的代碼。今天我們講一下&#xff0c;動態展示列表的列&#xff0c;因為找不到代碼了&#xff0c;所有本篇用圖展示。 舉個栗子 ?? 我們希望能夠動態的控制列表的列&#xff0c;例如&#xff0c;英語老師只想知道自己學…

Windows HD Video Converter Factory PRO-v27.9.0-

Windows HD Video Converter Factory PRO 鏈接&#xff1a;https://pan.xunlei.com/s/VOL9TaiuS7rXbu-1kEDndoceA1?pwd7qch# 支持300多種視頻格式轉換&#xff0c;在保留視頻質量的同時&#xff0c;壓縮率可達80%&#xff0c;轉換速度可達50X速率&#xff01; 支持畫面剪切、片…

C++程序設計語言筆記——抽象機制:構造、清理、拷貝和移動

0 應該將構造函數、賦值操作以及析構函數設計為一組匹配的操作。 在C中&#xff0c;構造函數、賦值操作符和析構函數共同管理對象的資源生命周期。為確保資源安全且一致地處理&#xff0c;需將它們作為一組匹配的操作設計。以下是關鍵要點&#xff1a; 為何需要協同設計&…

##Hive安裝-初始化元數據報錯 *** schemaTool failed ***

報錯&#xff1a; org.apache.hadoop.hive.metastore.HiveMetaException: Failed to get schema version. Underlying cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException : Communications link failure 解決方案&#xff1a; 嘗試一&#xff1a;javax.jdo.o…

遠程手機遙控開關原理及應用

遠程手機遙控開關的工作原理主要是通過互聯網傳遞無線信號&#xff0c;控制用電器的一種智能家居產品。 遠程手機遙控開關的基本套件包括&#xff1a;手機APP、網線、家用WIFI中轉無服務器或者是工廠提供的自帶網線端口的中轉服務器、連接用電器的接收器。使用時&#xff0c;手…

Mac java全棧開發環境配置

前言 由于最近手中的windows本子壞了,所以搞了一臺m系列的macbookpro 作為一個開發者 面對新設備最先考慮的應該就是各種sdk、中間件服務、環境變量配置和工具了吧!!! 本文將帶你手把手學習Mac搭建屬于自己的本地開發環境 安裝brew 什么是brew? ?Brew(全稱Homebrew)…

Ubuntu conda虛擬環境不同設備之間遷移

Ubuntu conda環境遷移&#xff08;conda-pack&#xff09; 方法一&#xff1a;壓縮拷貝方法二&#xff1a;conda-pack 在一臺電腦配置好conda虛擬環境后&#xff0c;若在其它電腦需要同樣的環境&#xff0c;可通過如下兩種方式進行遷移。 方法一&#xff1a;壓縮拷貝 找到Ubu…

詳細學習 pandas 和 xlrd:從零開始

詳細學習 pandas 和 xlrd&#xff1a;從零開始 前言 在數據處理和分析中&#xff0c;Excel 文件是最常見的數據格式之一。Python 提供了強大的庫 pandas&#xff0c;可以輕松地處理 Excel 文件中的數據。同時&#xff0c;我們還可以使用 xlrd 來讀取 Excel 文件&#xff0c;尤…

HTMLCSS繪制三角形

1.代碼&#xff1a; <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>01triangle</title><s…

vue3-element-admin 前后端本地啟動聯調

一、后端環境準備 1.1、下載地址 gitee 下載地址 1.2、環境要求 JDK 17 1.3、項目啟動 克隆項目 git clone https://gitee.com/youlaiorg/youlai-boot.git數據庫初始化 執行 youlai_boot.sql 腳本完成數據庫創建、表結構和基礎數據的初始化。 修改配置 application-dev.y…

C++中error C2027: 使用了未定義類型 問題部分解決方法

在 C 編程中&#xff0c;遇到錯誤 C2027&#xff1a;“使用了未定義類型”通常意味著在代碼中使用了某種類型&#xff0c;但是編譯器無法識別這個類型的定義。這個錯誤通常有幾個常見的原因&#xff1a; 1. 缺少包含頭文件 如果使用了某個庫中的類型&#xff0c;但是沒有包含…