如何暂停/恢复处理Lua命令
2011-5-26 21:5:32
收藏:0
阅读:126
评论:1
我正在编写一个客户端,它可以与多个服务器交流,并处理用户在stdin
(标准输入)上的命令,最后使用Lua从文件中读取。服务器是一个自定义应用程序,因此我正在处理所有与C
通信的代码,其中协议的所有代码都已经编写好了。这里是我现在的伪代码:
int main(int argc, char **argv) {
/* 设置fd列表,变量等 */
...
while (1) {
/* 处理文件描述符列表以创建读/写fd集 */
...
select(max, &read_fds, &write_fds, NULL, NULL);
for each file descriptor {
if (read fd is set) {
read data into a buffer
if (current fd is stdin)
process_stdin()
else if (current fd is from server connection)
process_remote()
}
if (write fd is set) {
write data on non-blocking fd
}
}
}
}
int process_stdin() {
luaL_loadbuffer(L, stdin_buffer, len, "stdin");
lua_pcall(L, 0, 0, 0);
}
int process_remote() {
parse buffer into message from remote system
if message is complete, call Lua with either a new message notification or resume
}
所以问题来了:如果用户在stdin
上输入类似wait_for_remote_message(xyz)
的内容,我该如何停止在那一点,从lua_pcall
中返回,并进入select
循环等待更多数据?然后,process_remote
如何从那一点恢复Lua命令?
我可以想象使用pthread的解决方案,但这感觉对于这个应用程序来说过于繁琐,并引入了很多额外的复杂性。
我还可以想象一种解决方案,其中while(1)/select
循环移动到一个函数中,并且从wait_for_remote_message(xyz)
返回到C
并使用stdin
添加到某种排除列表来调用此函数。
有更好的办法吗?
原文链接 https://stackoverflow.com/questions/6145059
点赞
评论区的留言会收到邮件通知哦~
推荐文章
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
- 如何编写 Lua 模式将字符串(嵌套数组)转换为真正的数组?
这似乎是 Lua 协程的一个完美应用,你可以调用 yield 暂停执行,然后稍后恢复。
详细信息请查看 http://www.lua.org/pil/9.html
你可以这样做:
int process_stdin() { lua_State coroutine = lua_newthread(L); luaL_loadbuffer(coroutine, stdin_buffer, len, "stdin"); if (lua_resume(coroutine, 0) == LUA_YIELD) { // 将协程存储在某个全局位置 } } int process_remote() { // 将缓冲区解析成来自远程系统的消息 // 将消息推送到 Lua 栈上 lua_resume(coroutine, 1); }