Jump to content

User:Cscott/Ideas/Improved for-loops for Lua/example1

From Wikipedia, the free encyclopedia
local function frame_args_to_table(frame)
    -- frame.args isn't a "real" table in Scribunto, so make one
    local list = {}
    local i = 1
    while frame.args[i] ~= nil do
        table.insert(list, frame.args[i])
        i = i + 1 
    end
    return list
end

return {
    max = function(frame, ...)
        local result = nil
        for _,item in ipairs(frame_args_to_table(frame)) with first, last do
            if first or item > result then
                result = item
            end
        then
            -- only if loop executed at least once
            return result
        else
            -- if loop never executed (no items in list)
            error("maximum of zero length list")
        end
    end,

    isprime = function(frame, ...)
        n = tonumber(frame.args[1])
        for x = 2, n-1 do
            if n % x == 0 then break end
        then
            return true
        else
            error("n was less than 2")
        end
        return false
    end,

    bignum_digits_to_string = function(frame, ...)
        s = ''
        for _,d in ipairs(frame_args_to_table(frame)) do
            s = s .. tostring(d)
        else
            -- if there are no digits in the digit list
            s = '0'
        end
        return s
    end,
    
}