mytable = setmetatable({key = 1},{__index = {key2 = 2}}) print(mytable.key) --1 print(mytable.key2) --2 1. 2. 3. 如果__index指向一个函数的话,Lua就会调用那个函数,table和key会作为参数传递给函数。 local function mymetatable(table,key) return "访问了table中不存在的key:"..key...
比如下面的:tb 是表不是数字,不能直接做加法,lua就会去看看 tb 表是不是有设置上了元表mt,然后才会去看看元表mt中的元方法,发现是有加法__add 这个元方法的存在,然后就调用该加法元方法。 tb = {a = 1} print(tb + 1) 4、重要且特殊的元方法 __index (1) 作用: table[key],当table不是表或是...
function gettable_event (table, key) local h if type(table) == "table" then local v = rawget(table, key) if v ~= nil then return v end h = metatable(table).__index if h == nil then return nil end else h = metatable(table).__index if h == nil then error(...); end en...
local part1 = "Hello, "local part2 = "how are "local part3 = "you?"local result = part1 .. part2 .. part3print(result) -- 输出: Hello, how are you?使用表连接字符串: 将字符串存储在表中,然后使用 table.concat 函数进行连接。local strings = {"Hello, ", "Lua!"}local result...
一定要注意,当记录式和列表式同时存在的时候,即使把记录式的构造元素放在前,table[1] 也是指列表式的第一个元素 使用以上两种构造器的时候都有各自的局限,比如对于特殊字符支持得不够,Lua 还有另外一种更加通用的构造器 opnames = {["+"] = "add", ["-"] = "sub", ["*"] = "mul", ["/"] = "...
使用表连接字符串: 将字符串存储在表中,然后使用table.concat函数进行连接。 localstrings = {"Hello, ","Lua!"}localresult = table.concat(strings)print(result) -- 输出: Hello, Lua! 使用迭代连接字符串: 可以使用迭代器将多个字符串连接起来。
m.__index = function ( table, key ) return "undefined" end --表pos pos = {x=1, y=2} --初始没有元表,所以没有定义找不到的行为 --因为z不在pos中,所以直接返回nil print(pos.z) -- nil --将pos的元表设为m setmetatable(pos, m) ...
(C)] */// 从第B个寄存器取出表,然后以RK(C)为Key取表的值给寄存器OP_GETTABLE,/* A B C R(A) := R(B)[RK(C)] */OP_SETTABUP,/* A B C UpValue[A][RK(B)] := RK(C) */OP_SETUPVAL,/* A B UpValue[B] := R(A) */OP_SETTABLE,/* A B C R(A)[RK(B)] := RK(C...
lua: /usercode/file.lua:3: attempt to perform arithmetic on local 't1' (a table value) 1. 因为程序不知道如何对两个表执行+运行,这时候就需要通过元表来定义如何执行t1的+运算,有点类似于c语言中的运算符重载。 local mt = {} --定义mt.__add元方法(其实就是元表中一个特殊的索引值)为将两个...
Example: TabArray2[2][3] will print 'Amazing' ]]TabDict1 = { --一个表字典a = 'banana',b = 'corn',c = 'eggplant'}--[[ Use tableName.key or tableName['key'] to access it!Example: TabDict1.a will print 'banana'Example: TabDict1['c'] will print 'eggplant' ]]TabDict2 ...