jawo
jawo

Reputation: 896

substring digit position that is nil

I'm about to point at specified digits in a string and alter them. An Input "ip_digit" and "pos" is given. "pos" specifies the digit to alter, ip_digit is the new value of the digit.

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

Output:
1234

The output is fine. Now I'm moving through the digits of the number in my terminal and alter the digit which the cursor is pointing. At the 3. Digit a > 0 < is inserted and can't be altered.

The Output now is:

12304

When I try to alter the '0-Digit', the 5. digit, which shouldn't be there, is altered instead.

How can that be? I thought port:sub(pos+1) could go one to far, but it doesn't.

EDIT:

ip_digit = com:read(nil) -- only accepted if 0-9
ip[port] = 1234

function replace_digit_in_IP(oct,pos)
if oct then -- issue is IP-Address
    do_something()
else -- issue is PORT
    port = tostring(ip["port"])
    os.syslog(ip["port"]) -- output is '1234' in example
    os.syslog(port) -- output is '1234' in example
    ip["port"] = tonumber(("%s%s%s"):format(port:sub(1,pos-1), ip_digit, port:sub(pos+1)))
    os.syslog(ip["port"]) -- output is 1234 or 12304 if 4th digit is altered.
end
cursorToNextBoxRight()--moves cursor one digit right in field, if there's none, move to digit at pos 1
os.syslog(string.format("x_index = %i,  y_index = %i",x_index,y_index)) -- debug(cursor pos)
print_menu()--prints text to terminal

end

replace_digit_in_IP(nil,3)

VISUALISING PROBLEM:

 1 2 3 4      (port-output)
 ^            (cursor)       

step "arrow-key-right"

1 2 3 4       (port-output)
  ^           (cursor)

step "input '9'" (numeric input also moves one right, after change)

1 9 3 4       (port-output)
    ^         (cursor)

step "input '9'" (move right)

1 9 9 0 4       (port-output)
      ^         (cursor)

step "input '9'" (move right, invalid so move to #1)

1 9 9 0 9       (port-output)
^               (cursor)

Upvotes: 0

Views: 63

Answers (1)

Oliver
Oliver

Reputation: 29591

I can't see anything wrong with your code, so the problem is elsewhere:

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)

Maybe syslog does not like numbers. Try removing your tostring and tonumber, and make ip['port'] always contain a string.

Upvotes: 0

Related Questions