Lua 使用string.gsub将空白更改为“不工作”
即使我使用gsub将空格改为uif语句仍然会出错尝试索引一个nil值我想知道是什么问题。我不能使用pairs,因为这是我老师给出的指令 这是代码对不起,我是初学者Lua 使用string.gsub将空白更改为“不工作”,lua,lua-table,Lua,Lua Table,即使我使用gsub将空格改为uif语句仍然会出错尝试索引一个nil值我想知道是什么问题。我不能使用pairs,因为这是我老师给出的指令 这是代码对不起,我是初学者 text = "ib c e d f" text = string.lower(text) b = text:gsub("%s+", "_") for k=1, #b do if not string.sub(b, k,k) or string.sub(b, k,k) ~= " " then if a[i][2]
text = "ib c e d f"
text = string.lower(text)
b = text:gsub("%s+", "_")
for k=1, #b do
if not string.sub(b, k,k) or string.sub(b, k,k) ~= " " then
if a[i][2] == string.sub(b, k,k) then
print(yes)
end
end
您的代码段中存在一些语法错误,导致您提到的错误。gsub函数实际上工作得很好
text = "ib c e d f"
text = string.lower(text)
b = text:gsub("%s+", "_") --> this gsub is working just fine
for k=1, #b do
if not string.sub(b, k,k) or string.sub(b, k,k) ~= " " then
if a[i][2] == string.sub(b, k,k) then --> you didn't assign any table called "a" before --> attempting to index a nil value
print(yes)
end
--> haven't close the "if not string.sub" function with an end
end --> this is the end for the loop "for k"
我只是疯狂地猜测,您希望将结果字符串与原始字符串进行比较。由于您的问题如此神秘,我只能提供以下代码供您参考:
text = "ab c d e f "
text = string.lower(text)
output = text:gsub("%s", "_")
for k = 1, #output do
local char = string.sub(output, k, k)
local originalChar = string.sub(text, k, k)
if (originalChar ~= " ") and (char == originalChar) then
print(char .. " --> OK")
end
end
gsub模式使用
%s
而不是%s+
,因此每个空格都转换为下划线,以便进行简单的单元测试(逐字符比较)。代码片段可用。什么是a[i][2]
?