Lua游戏开发,表似乎在每次交互后都会自行删除



我想做的是一个小插件,可以让我知道我在战斗中花了多少时间在 %,

function() 
local spell, _, _, _, _, endTime = UnitCastingInfo("player")
-- getting information from the game itself whether im "Casting"
local inCombat = UnitAffectingCombat("player")
-- getting information form the game if combat is true (1) or not (nil)
local casting = {}
local sum = 0
if inCombat == 1 then
if spell then 
table.insert(casting, 1)
else
table.insert(casting, 0)
end
else
for k in pairs (casting) do
casting [k] = nil 
end
end
for i=1, #casting, 1 do
sum = sum + casting[i]
end
return( sum / #casting ) end
-- creating a list which adds 1 every frame I am casting and I am in combat,
-- or adds 0 every frame I'm not casting and I'm not in combat.
-- Then I sum all the numbers and divide it by the number of inputs to figure 
-- out how much % I have spent "casting".
-- In case the combat condition is false, delete the list

由于某种原因,这些数字根本没有加起来,我只在满足两个条件时看到"1",如果满足战斗条件,我看到 0

。我敢肯定,可能会有一些更好的方法,但我对lua和编程有点陌生。

你说你是Lua的新手,所以我会尝试详细解释哪里出了问题以及如何改进它,所以请准备好长篇大论。

我假设你的函数将在游戏的每一帧/步骤/滴答/任何你想调用它的地方调用它。由于您在函数的开头设置了sum = 0casting = {},因此每次调用函数都会执行此操作。这就是为什么你最终总是得到 0 或 1。

上车救!

Lua有一个很好的东西,叫做词汇范围。我不会详细介绍,但基本思想是:如果在定义函数时变量可访问(在范围内(,则该函数会记住该变量,无论它在何处调用。例如:

local foo
do
local var = 10
foo = function() return var end
end
print(bar) -- nil
print(foo()) -- 10

您还可以为变量分配一个新值,下次调用该函数时,它仍将具有该新值。例如,下面是一个简单的计数器函数:

local counter
do
count = 0
counter = function() count = count + 1; return count; end
end
print(counter()) -- 1
print(counter()) -- 2
-- etc.

将其应用于您的情况,从一个调用到下一个调用需要保留哪些值?

  • 在战斗中花费的刻度数
  • 铸造所花费的刻度数

在函数外部定义这两个值,并根据需要递增/读取/重置它们;它将在对函数的重复调用之间持续存在。

要记住的事项:

  • 当玩家不再施法和/或战斗时,您需要重置这些计数器,否则它们只会从中断的地方继续。
  • casting不需要是表格。与整数相比,表速度较慢,即使您重复使用它们也是如此。如果你需要数东西,一个数字就绰绰有余了。只需在非战斗时制作casting = 0,在战斗中将其增加 1。

感谢您的反馈大家,最后在您的建议和一些研究之后,我的代码看起来像这样并且效果很好:

function() 
local spell, _, _, _, startTime, endTime, _, _, _ = UnitCastingInfo("player")
local inCombat = UnitAffectingCombat("player")
local inLockdown = InCombatLockdown()
local _, duration, _, _ = GetSpellCooldown("Fireball")
casting = casting or  {}
local sum = 0
if inCombat == 1 or inLockdown == 1 then 
if spell or duration  ~= 0 then 
casting[#casting+1] = 1  
elseif spell == nil or duration == 0  then
casting[#casting+1] = 0   
end  
else
local next = next
local k = next(casting)
while k ~= nil do
casting[k] = nil
k = next(casting, k)
end
end
for i=1, #casting, 1 do
sum = sum + casting[i]
end
return(("%.1f"):format( (sum / #casting)*100 ).. "%%") end

我注意到的是重置原始代码中的表存在问题:

for k in pairs (casting) do
casting [k] = nil

似乎要么一些零留在那里,要么表格大小没有"缩小"我不知道。

也许intereger会比表格更快,但老实说,即使表格变得大得离谱(5分钟,60 fps,即18k输入(,我也没有看到任何性能问题,也是为了学习一门新语言,在我看来最好以更难的方式做

问候

最新更新