Lua中如何将表元素转换为整数?
Got it, let's break this down for you since you're coming from Python and hitting that string-integer comparison snag in Lua. The core issue here is that when you split input into a Lua table, all elements default to strings—Lua doesn't auto-convert them like Python might in some contexts. But fixing this is straightforward with Lua's built-in tonumber() function, which is the equivalent of Python's int() for type conversion.
Step-by-Step Solution
1. Grab Input and Split It Into Strings
First, let's assume you're getting space-separated input from the user (like "5 10 15 20"). We'll use Lua's string pattern matching to split the input into a table of strings:
-- Read input from the user local input_str = io.read() -- Split the input string into a table of string elements local str_list = {} for str in string.gmatch(input_str, "%S+") do -- %S+ matches non-whitespace sequences table.insert(str_list, str) end
2. Convert Strings to Integers
Now, iterate over the string table and use tonumber() to convert each element to a numeric value. We'll build a new table for integers to keep things clean:
local int_list = {} for _, str in ipairs(str_list) do -- tonumber returns nil if the string can't be converted to a number local num = tonumber(str) if num then -- Only add valid numbers to avoid nil values in your list table.insert(int_list, num) end end
3. Use Your Integer List Without Errors
Now you can safely use int_list for comparisons or calculations without hitting those type mismatch errors. For example:
-- Example: Check which elements are greater than 10 for index, num in ipairs(int_list) do if num > 10 then print("Element at index", index, "is greater than 10:", num) end end
Why Your Earlier Conversion Attempt Might Have Failed
Chances are, one of these tripped you up:
- You forgot to assign the converted
tonumber()result back to the table (just callingtonumber(str)doesn't modify the original string) - You didn't handle cases where
tonumber()returnsnil(if the input has non-numeric characters, like letters) - You used a non-sequential loop (like
pairsinstead ofipairs) which can cause issues with ordered lists
Quick Streamlined Version
If you want to combine the split and conversion into one step to save lines:
local int_list = {} for str in string.gmatch(io.read(), "%S+") do local num = tonumber(str) if num then table.insert(int_list, num) end end
A quick reminder: Lua doesn't auto-convert strings to numbers in comparisons, so always make sure you've run tonumber() on input strings before doing any numeric operations. That's the key difference from Python here!
内容的提问来源于stack exchange,提问作者Rob

