Search code examples
rebolrebol3

How do I invoke an object function using its string name


Any idea why the following doesn't work? (R3)

o: make object! [
    foo: does [do "bar"]
    bar: does [print "hello from bar"]
]

o/foo
** Script error: bar has no value
** Where: catch either -apply- do foo
** Near: catch/quit either var [[do/next data var]] [data]

Solution

  • Try this:

    o: make object! [
        foo: does [do get bind load "bar" self]
        bar: does [print "hello from bar"]
    ]
    o/foo ;this will work
    

    You need that BINDing because your "bar" lives in the object, not in global scope.

    Check this out as well:

    my-func: does [print "ok"]
    o: make object! [
        foo: does [do "my-func"]
        bar: does [print "hello from bar"]
    ]
    o/foo ;this will work too
    

    You need to LOAD it because it is a string, but it has to be a word to be BINDed. So these will work too (put them in your object):

    do get bind to-word "bar" self
    

    or

    do get bind 'bar self