Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> can static: sections assign to an array that will be available at runtime?

The answer is yes, but it's a tad trickier than just accessing the compile-time list from run-time code (which doesn't make sense, and is illegal). Instead, use a macro to generate a bunch of run-time checks against a specific value. Eg:

  var eventNames {.compileTime.} = newSeq[string]()
  
  proc defineEvent(name:static[string]) =
    static:
      eventNames.add(name)
  
  macro checkDefined(name): stmt =
    # begin new statement
    result = newStmtList().add quote do:
      echo "Checking for '", `name`, "'"
    
    # loop over every known event name and
    # build a run-time 'if' check for each one.
    for n in eventNames:
      result.add quote do:
        if `n` == `name`:
          echo "Found it!"
  
  
  # add some events to compile-time list
  defineEvent("foo")
  defineEvent("bar")
  
  # define some runtime values
  let eventName1 = "foo"
  let eventName2 = "blah"
  
  # check runtime values againts compile-time list
  checkDefined(eventName1)
  checkDefined(eventName2)
  
  # output:
  #   Checking for 'foo'
  #   Found it!
  #   Checking for 'blah'
Note: This will inject a bunch of 'if' statements for each call to 'checkDefined', which might bloat your code.. it's probably better to make a macro which defines a proc, then just call that to check run-time values.. but I left those kinds of details out of this illustration for the sake of simplicity.


Thanks. I'm sure there's a way to promote a compile time seq into a constant runtime one. Might require some more macro trickery, though.


Err... what you said just reminded me of something, and I realized all the code I just showed you is really over-complicated and that Nim has much more straight forward options using `const`, like this:

  static:
    # define a compile-time list first
    var names = newSeq[string]()
    
    # add some values (at compile-time)
    names.add("foo")
    names.add("bar")

  # define the compiler vars as run-time const
  const runtimeNames = names

  # define some run-time variables
  var name1 = "foo"
  var name2 = "blah"

  # check runtime variables against const variable
  if runtimeNames.contains(name1): echo "Has Foo!"
  if runtimeNames.contains(name2): echo "Has Blah!"
Sorry about the rather winded (and bad example) replys :| But thanks for the conversation, it reminded me of this and now I have some cleaning up of my own code to get too. Cheers!




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: