0

在尝试解决如何使用精灵编程语言打印 sqlite 表内容的问题时,我发现我可以尝试调用 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 中正确运行回调?

4

1 回答 1

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

于 2015-12-05T10:32:24.023 回答