1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

色々な言語で簡単なREPLを実装する #lua

Last updated at Posted at 2023-12-06

続きです。

REPLとは

こちらの記事を参照してください。

Luaで実装する

main.lua

function main()
    local prompt = ""
    local event = ""

    while true do
        io.write("lua> ")
        prompt = io.read()

        if prompt == nil or prompt == "exit" then
            print("Bye!")
            break
        end

        -- eval(prompt)
        print(prompt)
    end
end

function eval(prompt)
    local func, err = load("return " .. prompt)
    if not func then
        print("Error: " .. err)
    else
        local ok, result = pcall(func)
        if ok then
            print(result)
        else
            print("Error: " .. result)
        end
    end
end

main()

実行する

$ lua main.lua
lua> 1 + 1
1 + 1
lua> foobar
foobar
lua> baz
baz
lua> exit
Bye!

ctrl-dのeofはprompt == nilで受けています。
evalはないっぽいので、少しごちゃごちゃ書いています。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?