当前位置: 代码迷 >> 综合 >> Lua5.3和Luajit踩坑攻略
  详细解决方案

Lua5.3和Luajit踩坑攻略

热度:72   发布时间:2023-11-25 23:02:09.0
  • Lua一大错觉,函数中的函数是局部遍历,其实全局的
  • 用goto实现continue,其中continue是变量,其实它不是,更没有局部和全局之分
  • Lua索引坚持用1,唯一不适应就是小心要+=index的时候,其它时候无所谓。知道for循环是<=的判别就好了。
  • Table在函数内是唯一引用,table直接赋值table的做法,就切断了联系,所以不起作用,如果只是改变属性还是有效果的
  • local函数中local变量作为参数的传递有些时序问题,暂时我不知道咋回事
  • Lua table血坑 这个对move函数也适用table.move(tbl,2,3,1,newtbl);
    • 不要数组和哈希混合用,当成数组就纯数组,当成哈希表就纯哈希表
    • 不要在数组中项,要移除就移除,千万不是为nil
    • 如果要以键值的形式对数组赋值,那设置值一定要从1开始,并且是连续的增长key,对应的赋值才可以
  • 警惕带BOM-UTF8文件,下面代码去除之
    UTF8Encoding utf8 = new UTF8Encoding(false);
  • 类的实例持有引用类型,都一样,但是lua中改变,可以让其它实例的引用也丢失? 如果持有不同的引用类型,那就在ctor里面new呢
TT = class("TT");
--TT.siki = siki;function TT:ctor()self.siki =siki;
endlocal t1 = TT.new();
local t2 = TT.new();
print(t1.siki);
print(t2.siki);t1.siki ={
    };
t2.siki =nil;print(t1.siki);
print(t2.siki);
print(TT.siki);
JK ={
    }
function JK:new(o)local o={
    }setmetatable(o,self);self.__index =self;o.siki =siki;return o;
endlocal j =JK:new();
local j2 =JK:new();j.siki ={
    };
j2.siki =nil;
print(j.siki);
print(j2.siki);
print(JK.siki);
  • XLua luaEnv.DoString($"require ('{requirePath}')", className);获取不到返回的lua table模块,答案前面加return

  • Lua事件模块还是自己写吧

event = {
    }--添加事件
function event.AddListener(eventType, func)if (eventType == nil or func == nil) thenerror('AddListener中eventType或func为空')returnendif (event[eventType] == nil) thenlocal a = {
    }table.insert(a, func)event[eventType] = aelsetable.insert(event[eventType], func)end
end--移除事件
function event.RemoveListener(eventType, func)if (eventType == nil or func == nil) thenerror('RemoveListener中eventType或func为空')returnendlocal a = event[eventType]if (a ~= nil) thenfor k, v in pairs(a) doif (v == func) thena[k] = nilendendend
end--派发事件
function event.SendEvent(eventType, ...)if (eventType ~= nil) thenlocal a = event[eventType]if (a ~= nil) thenfor k, v in pairs(a) dov(...)endendend
end
  • 良好的代码规范从现在开始,每写一段代码都要用心打造
  • 用github做代码版本管理,以及个人知识体系的打造
  • string.format(’%02d’, 1)在luajit不支持
  • 函数是字符串或table 可以省略(),但是只能是表达式不能是变量
  • 递归函数中,函数的变量名不要和函数中的局部变量重名了,会有bug
  • 堆排序有问题,暂时不知道怎么改

function heapfly(arr, n, d)if d >= (n-1) thenreturn ;endlocal max = d;local c1 = d * 2;local c2 = d * 2 + 1;if c1 <= n and arr[c1] > arr[max] thenmax = c1;endif c2 <= n and arr[c2] > arr[max] thenmax = c2;endif max ~= d thentable.swap(arr, max, d);heapfly(arr, n, max);end
end--10 5 4 1 2 3
function build_tree(arr, n)local index = #arr // 2;for i = index, 1, -1 doheapfly(arr, n, i);end
endfunction heap_sort(arr)build_tree(arr, #arr);for i = #arr, 1, -1 dotable.swap(arr, i, 1);heapfly(arr, i, 1);endendlocal arr = {
     2, 5, 3, 1, 10, 4 };
--10 5 3 4 1 2
heap_sort(arr);
table.print_arr(arr);
--[[ print(arr); heap_sort(arr); table.print_arr(arr) print(arr) ]]