能否请您提供一个代码片段来展示如何使用嵌入在 OCaml 中的 Lua?
一个简单的示例可能是“Hello, World”变体。让 OCaml 提示用户输入名称。然后将该名称传递给 Lua 函数。让 Lua 打印一个问候语并返回名称的长度。然后让 OCaml 打印一条关于名称长度的消息。
例子:
user@desktop:~$ ./hello.opt
姓名?用户
你好,用户。
你的名字有 4 个字母。
用户@桌面:~$
[编辑]
作为非 C 程序员,我是否可以在不必编写中间 C 程序来在 Lua 和 OCaml 之间传递数据的情况下实现这一点?
以下是我想尝试的理论想法。不幸的是,ocaml_hello.ml 的第 3 行需要知道如何调用 lua_hello.lua 中定义的函数才能使代码有效。
lua_hello.lua 定义 lua_hello,它打印一个参数并返回它的长度。
1 function lua_hello (name)
2 print ("Hello, "..name..".")
3 return (string.len (name))
4 end
ocaml_hello.ml OCaml 提示输入名称,调用 Lua 函数,并打印返回值。
1 let () = print_string "Name? "; flush stdout in
2 let name = input_line stdin in
3 let len = Lua_hello.lua_hello name in
4 Printf.printf "Your name is %d letters long." len; flush stdout;;