【问题标题】:How to use Sqlite.Callback in Genie如何在精灵中使用 Sqlite.Callback
【发布时间】:2015-12-05 00:05:08
【问题描述】:

在尝试解决问题How to print a sqlite table content with genie programming language 时,我发现我可以尝试调用 PrintSingleRecipe 作为 Database.exec 的回调。但是,回调似乎不能是常规函数,它们具有一些我似乎在互联网上找不到的属性。

我是这样称呼的:

else if response is "3" //Show a Recipe
    res:string = UserInterface.raw_input("Select a recipe -> ")
    sql:string = "SELECT * FROM Recipes WHERE pkID = %res"
    db.exec(sql, PrintSingleRecipe, null)

函数本身看起来像:

def PrintSingleRecipe(n_columns:int, values:array of string, column_names:array of string)
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    for i:int = 0 to n_columns
        stdout.printf ("%s = %s\n", column_names[i], values[i])
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "Ingredient list"
    print " "
    stdout.printf("%-5s", "%03i" )

但是,我在编译时收到以下错误:

valac --pkg sqlite3 --pkg gee-0.8 cookbook.gs
cookbook.gs:42.26-42.42: error: Argument 2: Cannot convert from `PrintSingleRecipe' to `Sqlite.Callback?'
            db.exec(sql, PrintSingleRecipe, null)
                         ^^^^^^^^^^^^^^^^^
Compilation failed: 1 error(s), 0 warning(s)

如何在 Genie 中正确运行回调?

【问题讨论】:

    标签: sqlite genie


    【解决方案1】:

    当函数作为参数传递时,Vala 编译器会对函数进行类型检查。当以这种方式使用函数时,它被称为“委托”。具体来说,Vala 编译器将检查函数的签名是否与委托类型定义的签名匹配。函数的签名由其参数类型和返回类型组成。 Cannot convert from 'PrintSingleRecipe' to 'Sqlite.Callback?' 表示PrintSingleRecipe 函数的签名与Sqlite.Callback 委托定义的签名不匹配。

    Sqlite.Callback 委托定义如下所示: http://valadoc.org/#!api=sqlite3/Sqlite.Callback 您已正确确定所需的参数是int, array of string, array of string,但您还需要包含返回类型。在这种情况下,它是int。所以你的回调应该是这样的:

    def PrintSingleRecipe(n_columns:int, 
            values:array of string, 
            column_names:array of string
            ):int
        print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
        for i:int = 0 to n_columns
            stdout.printf ("%s = %s\n", column_names[i], values[i])
        print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
        print "Ingredient list"
        print " "
        stdout.printf("%-5s", "%03i" )
        return 0
    

    返回非零值将中止查询。见https://www.sqlite.org/capi3ref.html#sqlite3_exec

    【讨论】:

    • 嗨AIThomas,如何从sql字符串中调用变量res?我使用的语法不起作用:res:string = UserInterface.raw_input("Select a recipe -> ") sql:string = "SELECT * FROM Recipes WHERE pkID = %res"
    • 您可以使用字符串连接:sql:string = "SELECT * FROM Recipes WHERE pkID = " + res 或模板:sql:string = @"SELECT * FROM Recipes WHERE pkID = $res"
    猜你喜欢
    • 2015-12-14
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    • 2015-05-02
    相关资源
    最近更新 更多