Is there a way to catch or intercept a proc call? Specifically one in another module. I posted some dummy files that show a flow similar to what my program is using.
lib.nim:
import random
proc action* =
# When working with main.nim, this is the only proc I care about
echo "Actions here"
proc checks(num: int) =
# To show that internal checks and calcs are done
if num == 1:
action()
proc step* =
# Simulate changing conditions
let chance = rand(1 .. 6)
checks(chance)
main.nim:
import ./lib
import std/monotimes
proc main =
var track: seq[MonoTime]
for a in 1 .. 10:
step()
# Need to print all the times of when lib.action ran
echo track
main()
There is context that exists in main.nim that doesn't and shouldn't exist in lib.nim which is why I can't just modify the lib to account for it. Any time lib.action runs, I want track in main to get updated with the time. Is this possible in the current state of the language, and if so, how?
There is context that exists in main.nim that doesn't and shouldn't exist in lib.nim which is why I can't just modify the lib to account for it.
Just modify the lib to account for it. There is no such thing as "context that is required but shouldn't exist" -- you don't clean designs by lying.
Maybe this suits your use case?
import ./lib
import std/monotimes
proc main =
var track: seq[MonoTime]
template doStep() =
track.add(getMonoTime())
step()
for a in 1 .. 10:
doStep()
echo track
main()
The issue is that I'm dealing with complex custom objects and the only way I see to properly add the context to lib.nim would be to merge the two files which defeats the purpose of many of the abstractions I made. I'd argue that if an catching/wrapping the action call is the cleanest way to implement the functionality I want. After all, lib.nim is supposed to be a generic lib for multiple different projects I'm working on with main.nim being one of the specializations. If it's simply not possible, please tell me and I'll go back to the drawing board in my design.
As for @Hlaaftana: I only want to do track.add(getMonoTime()) when lib.action triggers. Not for every step call.
lib.nim:
import random
import std/monotimes
var list: ref seq[Monotime]
new list
proc action* =
echo "Actions here."
proc check(num: int) =
if num == 1:
list[].add(getMonoTime())
action()
proc makeStep*(): ((proc(): void), ref seq[Monotime]) =
let step = proc() {.closure.} =
let val = rand 1..6
check val
(step, list)
main.nim:
import lib
when isMainModule:
var (step, list) = makeStep()
for a in 1..10:
step()
echo list[]
Can this approach be used?