Lua代码索引嵌套表报错:attempt to index a string value(field '?') 求助
Let's fix your Lua code and resolve that error step by step
First, let's break down exactly what's causing the attempt to index a string value error:
1. The core issue: Prematurely converting a subtable to a string
Your code converts the subtable storing byte values to a string inside the inner character-loop. Here's what happens:
- When you process the first character of a line, you add its byte value to
Table[#Table](a subtable) - Immediately after, you run
Table[#Table] = table.concat(Table[#Table]), turning that subtable into a string - When the loop moves to the second character, you try to do
Table[#Table][i] = ...— but nowTable[#Table]is a string, not a table. Lua can't index a string like a table for assignment, hence the error.
2. A secondary typo
Your final print statement uses table.concat(table) — here, table refers to Lua's global table type, not your custom Table variable. This would cause another error once the first issue is fixed.
Corrected Code
local file = assert(io.open("E:\\text.txt","r")) local Table = {} local function Sort() -- Rename loop variable to "line" for better readability for line in file:lines() do local byteSubtable = {} print(line) -- Process all characters in the current line first for i = 1, #line do table.insert(byteSubtable, string.byte(line, i, i)) end -- Only convert the subtable to a string after processing all characters Table[#Table + 1] = table.concat(byteSubtable) print("hi") -- Fix the typo: use your custom Table variable print(table.concat(Table)) end -- Always close files to avoid resource leaks file:close() end Sort()
Key Fixes Explained
- Moved the
table.concatcall outside the inner character-loop: We now build the full subtable of byte values first, then convert it to a string once per line. - Fixed the typo in the final print statement to reference your
Tablevariable instead of Lua's globaltabletype. - Added
file:close()to clean up the file handle after reading (a critical best practice). - Used a local variable
byteSubtablefor clarity, making the code easier to follow.
内容的提问来源于stack exchange,提问作者eye science international
相关产品推荐
相关产品推荐

