You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 now Table[#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.concat call 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 Table variable instead of Lua's global table type.
  • Added file:close() to clean up the file handle after reading (a critical best practice).
  • Used a local variable byteSubtable for clarity, making the code easier to follow.

内容的提问来源于stack exchange,提问作者eye science international

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:07:13