lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Unless a string has a special character code in in front of the number, tonumber does a literal conversion of the string:

tonumber("10000") = 10000
tonumber("00100") = 00100

add them together and you get 10100, with tostring and match it will give you nil use it with 11100 and 00111 and you get 11211, so match will give one match



Adrien de Croy wrote:

how can adding 2 numbers, converting it to a string, then pattern matching it to "2" do anything useful? string.match returns either a substring or nil. So, you'll get something non-nil if the result of the addition contains the digit 2 in decimal. That's certainly not what was requested?

e.g. take 10000 and 00100, no matching bits but

16 + 4 = 20, which contains "2"

without bit-wise operators in lua (e.g. XOR), you're going to need to go through the digits one at a time I'm afraid...




Merick wrote:
Shmuel Zeigerman wrote:
Merick wrote:
I was wondering if there was any way - other than using a for loop to iterate through each character - to use the string library to compare two strings with representations of binary numbers and tell whether or not any of the 1's in the strings are in the same position?

Something like compare("11100", "00011") would return false and compare("11100","00111") would return true


function compare(a,b)
  a = tostring(tonumber(a) + tonumber(b))
  return a:match"2"
end

Dangit, that's so simple I can't believe I didn't think of it myself!

Thanks