子字符串数字位置为空。

我将要在一个字符串中指定数字并改变它们。 给定一个输入“ip_digit”和“pos”。 “pos”指定要更改的数字,ip_digit是数字的新值。

port = "1234"
ip["port"] = tonumber(("%s%s%s"):format(port:sub(1,pos-1), ip_digit, port:sub(pos+1)))
print(ip["port"])

输出:

1234

输出正常。现在我正在通过终端中的数字移动并更改指向游标的数字。在第三个数字中,插入>0<,不能修改。 现在的输出是:

12304

当我试图更改“0-Digit”,第五个数字中出现的不应该存在的“5”被修改了。

为什么会这样?我认为'port:sub(pos+1)'可能会走得太远,但事实并非如此。

编辑:

ip_digit = com:read(nil) -- 只接受0-9
ip[port] = 1234

function replace_digit_in_IP(oct,pos)
if oct then -- 问题是IP地址
    做一些事情()
else -- 问题是端口
    port = tostring(ip["port"])
    os.syslog(ip["port"]) -- 输出示例中为“1234”
    os.syslog(port) -- 输出示例中为“1234”
    ip["port"] = tonumber(("%s%s%s"):format(port:sub(1,pos-1), ip_digit, port:sub(pos+1)))
    os.syslog(ip["port"]) -- 输出为1234或12304(如果更改第4位数字)。
end
cursorToNextBoxRight()--将光标移动到字段中的一个数字向右,如果不存在,则移动到位置1处的数字
os.syslog(string.format("x_index = %i,  y_index = %i",x_index,y_index)) -- 调试(光标位置)
print_menu()--将文本打印到终端

end

replace_digit_in_IP(nil,3)

可视化问题:

 1 2 3 4      (端口输出)
 ^            (光标)

步骤“向右箭头”

1 2 3 4       (端口输出)
  ^           (光标)

步骤“输入'9'”(数字输入也向右移动,更改后)

1 9 3 4       (端口输出)
    ^         (光标)

步骤“输入'9'”(向右移动)

1 9 9 0 4       (端口输出)
      ^         (光标)

步骤“输入'9'”(向右移动,无效,因此转到#1)

1 9 9 0 9       (端口输出)
^               (光标)

原文链接 https://stackoverflow.com/questions/25383982

点赞
stackoverflow用户869951
stackoverflow用户869951

我没有看出你的代码有什么问题,所以问题可能出在其他地方:

function replace_digit_in_IP(port, pos, digit)
    port = tostring(port)
    port = ("%s%s%s"):format(port:sub(1,pos-1), digit, port:sub(pos+1))
    return tonumber(port)
end

port = 1234
port = replace_digit_in_IP(port, 1, '9')
print(port)
port = replace_digit_in_IP(port, 2, '8')
print(port)
port = replace_digit_in_IP(port, 3, '7')
print(port)
port = replace_digit_in_IP(port, 4, '6')
print(port)

也许 syslog 不支持数字。尝试删除 tostringtonumber,并将 ip['port'] 始终设置为字符串。

2014-09-02 04:46:09