Lua: Markov-chain algorithm error

我正在尝试运行我的代码,但是当我运行它时,它会给我一个错误:

input:1: 尝试对一个空值进行索引(全局变量 'arg')。

我不知道如何排除故障。

这是我的代码:

function allwords()
    local line = io.read()    -- 当前行
    local pos = 1             -- 当前行中的当前位置
    return function()        -- 迭代器函数
        while line do           -- 循环直到文件末尾
            local s, e = string.find(line, "%w+", pos)
            if s then      -- 找到一个单词?
                pos = e + 1  -- 更新下一个位置
                return string.sub(line, s, e)   -- 返回这个单词
            else
                line = io.read()    -- 找不到单词;尝试读取下一行
                pos = 1             -- 从第一个位置重新开始
            end
        end
    return nil            -- 没有更多行:遍历结束
    end
end

function prefix(w1, w2)
    return w1 .. ' ' .. w2
end

local statetab

function insert(index, value)
    if not statetab[index] then
        statetab[index] = {n=0}
    end
    table.insert(statetab[index], value)
end

local N  = 2
local MAXGEN = 10000
local NOWORD = "\n"

构建表格

statetab = {}
local w1, w2 = NOWORD, NOWORD
for w in allwords() do
    insert(prefix(w1, w2), w)
    w1 = w2; w2 = w;
end
insert(prefix(w1, w2), NOWORD)

生成文本

w1 = NOWORD; w2 = NOWORD     -- 重新初始化
for i=1,MAXGEN do
    local list = statetab[prefix(w1, w2)]
    -- 从列表中随机选择一个项目
    local r = math.random(table.getn(list))
    local nextword = list[r]
    if nextword == NOWORD then return end
    io.write(nextword, " ")
    w1 = w2
    w2 = nextword
end

如何修复它?

点赞