As written in the comments to your question, the pdf/xe/luatex engine does not parse the file to find any hint for the needed TeX-engine.
But your editor can do this. Well, if you are using Emacs, e.g.
Emacs comes with a "mode" called AUCTeX. This mode checks for local variables. If you write this code at the end of your file, AUCTeX will use LuaTeX to compile:
%%% Local Variables:
%%% TeX-engine: luatex
%%% TeX-master: t
%%% End:
So as soon as you are writing something like \directlua{...}
, add the local variables to your file.
iflua
package?%!TEX luatex
at the top to make it use luatex. But it is editor specific and you have not said which you are using.