展示HN:我用C语言构建了一个简约的类Forth栈解释器库

3作者: Forgret3 个月前原帖
这个周末我创建了 stacklib.h —— 一个单头文件库,将 Forth 风格的栈操作引入 C 语言。它实现了一个基本的解释器,包含以下功能: - 栈操作(push/pop/dup/swap/over/drop) - 算术运算(+, -, *, /) - 输出(., emit, cr) - 栈检查(.s, depth) 示例用法: ```c Stack s; stack_init(&s); dict_init(); exec(&s, "10 20 + ."); // 输出 "30" exec(&s, "1 2 3 4 .s"); // 显示栈内容 ``` 这个库是自包含的,不需要任何依赖,并且处理基本的错误检查。它的灵感来源于想要理解 Forth 的基本工作原理,同时保持 C 语言的简单性。 我很好奇其他栈式或连接式编程爱好者对这种方法的看法。还有其他人构建过类似的东西吗?你会添加哪些功能以使其更有用? GitHub: [https://github.com/Ferki-git-creator/stacklib](https://github.com/Ferki-git-creator/stacklib)
查看原文
This weekend I created stacklib.h - a single-header library that brings Forth-style stack operations to C. It implements a basic interpreter with:<p>- Stack operations (push&#x2F;pop&#x2F;dup&#x2F;swap&#x2F;over&#x2F;drop) - Arithmetic (+, -, *, &#x2F;) - Output (., emit, cr) - Stack inspection (.s, depth)<p>Example usage: Stack s; stack_init(&amp;s); dict_init(); exec(&amp;s, &quot;10 20 + .&quot;); &#x2F;&#x2F; Prints &quot;30&quot; exec(&amp;s, &quot;1 2 3 4 .s&quot;); &#x2F;&#x2F; Shows stack contents<p>The library is self-contained, requires no dependencies, and handles basic error checking. It was inspired by wanting to understand how Forth works at a fundamental level while keeping the simplicity of C.<p>I&#x27;m curious what other stack-based or concatenative programming enthusiasts think about this approach. Has anyone else built something similar? What features would you add to make it more useful?<p>GitHub: <a href="https:&#x2F;&#x2F;github.com&#x2F;Ferki-git-creator&#x2F;stacklib" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;Ferki-git-creator&#x2F;stacklib</a>