简体   繁体   English

为什么我不能让 bool 在 Solidity Assembly function 中正常工作?

[英]Why can't I get bool to work properly in Solidity Assembly function?

I'm making an IsPrime function using Solidity Assembly code.我正在使用 Solidity 汇编代码制作 IsPrime function。

The function takes a number as parameter and returns true for prime, and false otherwise. function 接受一个数字作为参数,如果是素数则返回 true,否则返回 false。

I've gotten my function to work, but I had to do a workaround outside of the assembly code.我已经让我的 function 工作了,但我不得不在汇编代码之外做一个解决方法。

See the code below:请参阅下面的代码:

// SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.4.26;

contract PrimeNumber{

    function isPrimeNumber(uint num1) public view returns(bool) {
        
        uint result = 20;  // bool result = true;
        

        assembly{
    
            for {let i := 2} lt(i, num1) {i := add(i, 1)}{
                if eq(mod(num1, i), 0) {result := 10}  // result := false
            }
        
         

        }
        if(result == 10){
            return false;
        }
        return true;  // return result;
    }
}


So the function works, but I can't for the life of me, get it to work properly using only BOOL and assembly.所以 function 可以工作,但我不能只使用 BOOL 和汇编让它正常工作。

I had to add a normal if/else statement after the assembly because I could only get the result to work properly as a UINT type.我不得不在汇编后添加一个普通的 if/else 语句,因为我只能让结果作为 UINT 类型正常工作。

I've tried switch statements but I get the error "true and false are not valid literals"我试过 switch 语句,但出现错误“true 和 false 不是有效文字”

See comments for what I want to do.查看评论了解我想做什么。

Solidity assembly is not able to work with true and false literals until Solidity version 0.6.在 Solidity 版本 0.6 之前, false true I haven't found any info about this in the docs - only validated by trying different versions.我没有在文档中找到任何关于此的信息 - 只能通过尝试不同的版本来验证。

You can bypass this limitation by using false-like value, eg 0.您可以使用类似 false 的值(例如 0)来绕过此限制。

pragma solidity ^0.4.26;

contract PrimeNumber{
    function isPrimeNumber(uint num1) public view returns(bool) {
        bool result = true;
        assembly{
            for {let i := 2} lt(i, num1) {i := add(i, 1)}{
                if eq(mod(num1, i), 0) {
                    result := 0
                }
            }
        }
        return result;
    }
}

Note: Latest version of Solidity (November 2022) is 0.8.17.注意:最新版本的 Solidity(2022 年 11 月)是 0.8.17。 So if your use case allows it, I'd recommend you to use the latest version as it contains bug fixes and security improvements.因此,如果您的用例允许,我建议您使用最新版本,因为它包含错误修复和安全改进。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM