return a strdef?

Anything that doesn't fit elsewhere.
Post Reply
eacheon
Posts: 97
Joined: Wed Jan 18, 2006 2:20 pm

return a strdef?

Post by eacheon »

Can I return a strdef variable as the return value of a function in hoc?

Seems obfunc should do the job, but it does not work for me...

Code: Select all

oc>obfunc a() {
>       oc>return "fdasf"
>       oc>}
oc>a()
        0 
oc>strdef s  
oc>s = a()
bad stack access: expecting (char *); really (double)
nrniv: interpreter stack type error
 near line 8
 s = a()
ted
Site Admin
Posts: 6305
Joined: Wed May 18, 2005 4:50 pm
Location: Yale University School of Medicine
Contact:

Use the standard run system's String class

Post by ted »

You have stumbled upon something that is an accident of history. In NEURON's early
incarnations, hoc had scalars, doubles (arrays), sections, and strdefs (strings).
Object-oriented programming was added later, and with it came objrefs. Consequently
doubles, sections, and strdefs "aren't quite objects," and that's why and obfunc won't
return any of these.

That's no problem as far as doubles are concerned--the Vector class, which is so much
more powerful and flexible, has replaced the use of doubles in any new code development.
The SectionRef and SectionList classes allow sections to be passed as arguments to
a function, and returned as results from obfuncs.

But what to do about strings? You might be able to take advantage of the fact that
strdefs are passed by reference. For example

Code: Select all

oc>strdef fap
oc>fap = "original string"
oc>fap
original string
oc>proc foo() { $s1="new version" }
oc>foo(fap)
oc>fap
new version
Alternatively, you could use an object as a wrapper for a strdef. The standard run
system--which you get by including the statement
load_file("nrngui.hoc")
in your hoc code--defines the String class. This code is excerpted, sans comments,
from stdlib.hoc:

Code: Select all

begintemplate String
public s
strdef s
  proc init() {
        if (numarg() == 1) {
                s = $s1
        }
  }
endtemplate String
Example:

Code: Select all

oc>objref foo, fap
oc>foo = new String()
oc>foo.s="bla"
oc>foo.s
        bla
oc>fap = new String("blabla")
oc>fap.s
        blabla
So instead of an obfunc that returns a strdef, you would write an obfunc that returns a
String.
Post Reply