5

我正在尝试将字符串值存储到变量中。要定义变量,我使用:

: define CREATE 0 , ;
define x

我可以轻松存储整数/浮点值以x使用

10 x !

或者

10.0e x f!

为了访问它,我使用@f@。现在我正在尝试存储一个字符串值:

s" hello world" x !

这样做的问题是它将两个值推送到堆栈(因为它是一个计数字符串),但x !只会将项目存储在顶部,即字符串的长度。这是危险的,因为堆栈内容可能在被x引用时已被修改,因此地址不直接低于长度(糟糕!),因此type会失败。所以我的问题是,有没有办法将两个值(地址和长度)存储到x?或者是否有不同的数据类型/操作数可以让我实现这一目标?

任何帮助表示赞赏。

4

4 回答 4

3

完成这项工作所需的许多东西都与您已经拥有的东西非常相似。

define如果你想在你用它创建的东西中存储两个值,你需要一个不同的版本;

: 2define create 0 , 0 , ;

将两个放在单词的开头是一种约定,表明它与没有两个的单词做同样的事情,而是在双单元格的事情上做。

要使用它,您将编写:

2define 2x
//Write something to 2x
s" Hello world!" 2x 2!
//Retrieve it and print
2x 2@ type

值得注意的是,s"返回的地址不能保证持续程序的持续时间,并且可能会被以后使用的覆盖s",以查看一种方法来制作保证持续的字符串变量看看这个答案https ://stackoverflow.com/a/8748192/547299(有点啰嗦,但有一个叫做的词的定义string可能是说明性的)。

于 2014-03-14T22:25:23.027 回答
1

Gforth has a $! ( c-addr u addr -- ) word precisely for this purpose. Given a string and an address, it copies the string into a freshly ALLOCATEd space and stores the string at the address. If the address already has a string stored at it, that string will be FREEd.

So:

define x
s" hello world" x $!

x $@ type  \ hello world

You can also use fixed buffers with counted strings and words like PLACE and +PLACE , which have $!'s same stack picture. Equivalently to the above (although with a character limitation):

256 buffer: x
s" hello world" x place

x count type  \ hello world

s" !" x +place
x count type  \ hello world!
于 2014-06-25T00:15:35.533 回答
1

不要卡在“!”上。这样更有效率...

: 2x S" Hello World!" ;

此外,define 对浮点数不安全,它可能是

   : define CREATE 0 f, does> f@ ;
 \   3.1459e0 define pi
 \   pi f. 3.1459 ok
于 2014-04-07T21:03:46.230 回答
0

您不能将字符串存储在 Forth 意义上的 VARIABLE 中。VARIABLE 最多可以容纳 2 个 4 或 8 个长度的字符串,具体取决于 Forth。如果要存储字符串,则需要缓冲区。缓冲区必须至少比字符串长(呃!),并且字符串的长度必须与它一起存储,以适应字符串的正常含义。除了分配正确大小的缓冲区之外,您还必须执行以下操作。

1024 CONSTANT SIZE \ Pray this is enough
CREATE BUFFER SIZE ALLOT
"AAP" BUFFER $! 

引用的字符串是 2012 标准,离开 (地址, 长度)。美元!留作练习。^H^H^H^H^H^H

: $! ( cs s -- ) 2DUP ! CELL+ SWAP CMOVE ; 
于 2021-11-28T16:26:00.263 回答