Introspection: Difference between revisions

Frink
No edit summary
(Frink)
 
(28 intermediate revisions by 20 users not shown)
Line 12:
=={{header|Ada}}==
Ada doesn't allow you to ask about compiler versions, but you can query specific parameters of the target, such as the range of the standard integer type, or the precision of the standard floating point type:
<langsyntaxhighlight lang="ada">with Ada.Integer_Text_IO, Ada.Text_IO;
procedure Introspection is
use Ada.Integer_Text_IO, Ada.Text_IO;
Line 25:
Put (Float'Digits);
New_Line;
end Introspection;</langsyntaxhighlight>
All Ada compilers recognize obsolete parts of a programs and either automatically recompile them or fail to link the program.
 
=={{header|Aikido}}==
The version of the Aikido interpreter is in the global scope variable <em>version</em>. AIkido doesn't have <code>abs</code> but it does have <code>fabs</code>. Getting the variables in main involves getting their names and then evaluating them as an expression in order to retrieve their type.
<langsyntaxhighlight lang="aikido">
import math
 
Line 83:
 
 
</syntaxhighlight>
</lang>
Here is the result:
fabs(bloop) is 1.4
There are 3 integer variables in the global scope
Their sum is 1936
 
 
 
=={{header|ALGOL 68}}==
Line 103 ⟶ 101:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<langsyntaxhighlight lang="algol68">BEGIN
print (("Integer range: ", -max int, " .. ", max int, new line));
print (("Integer digits: ", int width, new line));
print (("Float range: ", -max real, " .. ", max real, new line));
print (("Float digits: ", real width, new line))
END</langsyntaxhighlight>
{{out}}
<pre>
Line 123 ⟶ 121:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - MODEs BYTE, SEMA, FORMAT etc are not available in ELLA Algol68RS}}
<langsyntaxhighlight lang="algol68">BEGIN
MODE SSMODES = UNION(SHORT SHORT BITS, SHORT SHORT BYTES, #SHORT SHORT CHAR,#
SHORT SHORT INT, SHORT SHORT REAL, SHORT SHORT COMPL);
Line 172 ⟶ 170:
sep := ", "
OD
END</langsyntaxhighlight>
{{out}}
<pre>
Line 186 ⟶ 184:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-2.3.3 algol68g-2.3.3].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
'''File: Typeof_operator.a68'''<langsyntaxhighlight lang="algol68">#!/usr/local/bin/a68g --script #
 
OP TYPEOF = (INT skip)STRING: "INT";
Line 193 ⟶ 191:
OP TYPEOF = (COMPL skip)STRING: "COMPL";
 
printf(($g" "$,TYPEOF 1, TYPEOF "x", TYPEOF pi, TYPEOF (0 I 1 ), $l$))</langsyntaxhighlight>
{{out}}
<pre>
Line 205 ⟶ 203:
{{works with|ELLA ALGOL 68|Any (with appropriate job cards)}}
 
'''File: Introspection_array_bounds.a68'''<langsyntaxhighlight lang="algol68">#!/usr/local/bin/a68g --script #
 
[]INT x = (5,4,3,2,1);
 
print(("x =", x, new line));
print(("LWB x =", LWB x, ", UPB x = ",UPB x, new line))</langsyntaxhighlight>
{{out}}
<pre>
Line 216 ⟶ 214:
LWB x = +1, UPB x = +5
</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">if not? sys\version > 0.9.0 -> panic "version too old!"
 
bloop: 3 - 5
 
if? set? 'bloop -> "variable 'bloop' is set"
else -> "variable 'bloop' is not set"
 
if set? 'abs -> print ["the absolute value of bloop is:" abs bloop]
 
print [
"The sum of all globally defined integers is:"
sum map select keys symbols 'sym -> integer? var sym
'sym -> var sym
]</syntaxhighlight>
 
{{out}}
 
<pre>the absolute value of bloop is: 2
The sum of all globally defined integers is: -2</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">if (A_AhkVersion < "1.0.48.03")
{
MsgBox % "you are using" . A_AhkVersion . "`nplease upgrade to" . "1.0.48.03"
Line 227 ⟶ 247:
if IsFunc("abs")
MsgBox % abs(bloop)
return</langsyntaxhighlight>
 
=={{header|AWK}}==
{{works with|gawk|4.1.0}} PROCINFO is a gawk-extension
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f INTROSPECTION.AWK
BEGIN {
Line 246 ⟶ 266:
}
function abs(x) { if (x >= 0) { return x } else { return -x } }
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 255 ⟶ 275:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> IF VAL(FNversion) < 5.94 THEN PRINT "Version is too old" : END
ON ERROR LOCAL PRINT "Variable 'bloop' doesn't exist" : END
Line 277 ⟶ 297:
INPUT #F%,V$
CLOSE #F%
= RIGHT$(V$,5)</langsyntaxhighlight>
 
=={{header|C}}==
Line 285 ⟶ 305:
 
{{works with|C|94 and later}}
<langsyntaxhighlight lang="c">#if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L
#pragma error("C compiler must adhere to at least C99 for the following code.")
#else
/* rest of file */
#endif</langsyntaxhighlight>
 
However, there is no facility in C for checking whether individual variables
Line 296 ⟶ 316:
doing this kind of check in a shell script and defining symbols
such as HAVE_ABS which ''can'' be checked by the preprocessor.
 
=={{header|C sharp|C#}}==
There has to be some caveats made with C#. There are no truly "global" variables - just publicly exported ones from individual classes/types. I chose to make a couple of public static variables in my program's class. Also, the "version" of the compiler is difficult to impossible to get at. There are no predefined compiler constants that can be compared against as in C/C++ but then again, it's hardly the thing that counts in C#. What really counts is the version of .NET and the framework you're working with since that determines what C++ features you can use and the various calls that can be made. Consequently, I check the .NET version to make sure it's past 4.0 and exit if not.
<langsyntaxhighlight lang="csharp">using System;
using System.Reflection;
 
Line 379 ⟶ 400:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
<pre>bloop's abs value = 10
2 exported ints which total to -30</pre>
 
=={{header|C++}}==
Identifying the version of the C++ standard used by the compiler in C++ is syntactically very similar to the way of checking the C standard version (also seen on this page).
 
<syntaxhighlight lang="cpp">#if !defined(__cplusplus) || __cplusplus < 201103L
#pragma error("The following code requires at least C++11.")
#else
// ...
#endif</syntaxhighlight>
 
As in C, the introspective capabilities of C++ are very limited.
 
=={{header|Clojure}}==
Partial answer...
<langsyntaxhighlight lang="clojure">
; check Java version
(let [version (Double/parseDouble (re-find #"\d*\.\d*" (System/getProperty "java.version")))]
Line 399 ⟶ 431:
(println "Version ok")
(throw (Error. "Bad version"))))
</syntaxhighlight>
</lang>
 
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(let* ((ver (lisp-implementation-version))
(major (parse-integer ver :start 0 :end (position #\. ver))))
#+lispworks (assert (>= 5 major) () "Requires Lispworks version 5 or above")
#+clisp (assert (>= 2 major) () "Requires CLISP 2.n")
)</langsyntaxhighlight>
<langsyntaxhighlight lang="lisp">(defvar bloop -4)
(if (and (fboundp 'abs)
(boundp 'bloop))
(format t "~d~%" (abs bloop)))</langsyntaxhighlight>
The ''list-all-packages'' and ''do-symbols'' forms enable a lisp program to examine all symbols and these can be tested to identify integer variables.
<langsyntaxhighlight lang="lisp">(let ((sum 0)
(ints '()))
(loop for pkg in (list-all-packages)
Line 422 ⟶ 453:
(incf sum (symbol-value s)))))
(format t "there are ~d integer variables adding up to ~d~%"
(length ints) sum))</langsyntaxhighlight>
 
=={{header|D}}==
With extra credit.
<langsyntaxhighlight lang="d">// Some module-level variables (D doesn't have a global scope).
immutable x = 3, y = 100, z = 3_000;
short w = 1; // Not an int, must be ignored.
Line 457 ⟶ 488:
tot += mixin("." ~ name);
writeln("Total of the module-level ints (could overflow): ", tot);
}</langsyntaxhighlight>
{{out}}
<pre>The expression is compilable.
Line 464 ⟶ 495:
=={{header|E}}==
Version:
<langsyntaxhighlight lang="e">def version := interp.getProps()["e.version"]</langsyntaxhighlight>
 
(There is no built-in version comparison, and the author of this example assumes that implementing a version comparison algorithm isn't the point of this task.)
 
Existence:
<langsyntaxhighlight lang="e">escape fail {
def &x := meta.getState().fetch("&bloop", fn { fail("no bloop") })
if (!x.__respondsTo("abs", 0)) { fail("no abs") }
x.abs()
}</langsyntaxhighlight>
 
This will return either bloop.abs(), "no bloop", or "no abs".
 
Sum of integers:
<syntaxhighlight lang="e">{
<lang e>{
var sum := 0
for &x in interp.getTopScope() { sum += try { x :int } catch _ { 0 } }
sum
}</langsyntaxhighlight>
<code>try</code> rather than an ordinary type check is used because in general a slot might be broken; this way we skip over all read failures as well as non-integers. The block around the code ensures that the sum variable itself will not be involved in the computation.
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(version)
→ EchoLisp - 2.50.3
Line 515 ⟶ 546:
 
 
</syntaxhighlight>
</lang>
 
=={{header|Erlang}}==
Erlang does not have global variables so I look for a function bloop/0 that returns an integer.
Moreover, I sum the available modules, instead of the unavailable global integers.
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( introspection ).
 
Line 541 ⟶ 572:
exit_if_too_old( Release ) when Release < "R13A" -> erlang:exit( too_old_release );
exit_if_too_old( _Release ) -> ok.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 551 ⟶ 582:
=={{header|Factor}}==
Check for build number and execute a quotation if it's too old. (There are no such things as versions for Factor yet.)
<langsyntaxhighlight lang="factor">: if-older ( n true false -- )
[ build > ] 2dip if ; inline
 
Line 559 ⟶ 590:
[ [ ] ] dip if-older ; inline
 
900 [ "Your version of Factor is too old." print 1 exit ] when-older</langsyntaxhighlight>
 
It is possible to test if a function or a variable exists (<code>search</code>), but that shouldn't be used outside of parsing.
<langsyntaxhighlight lang="factor">"bloop" search [
get [
"abs" search [ execute( n -- n' ) ] when*
] [ 0 ] if*
] [ 0 ] if*</langsyntaxhighlight>
 
On the other hand, it is possible to search the global namespace for integer variables:
<langsyntaxhighlight lang="factor">USING: assocs formatting kernel math namespaces ;
 
0 0
Line 575 ⟶ 606:
nip dup integer? [ + [ 1 + ] dip ] [ drop ] if
] assoc-each
"There are %d integer variables, the sum is %d\n" printf</langsyntaxhighlight>
 
=={{header|Forth}}==
Standard Forth doesn't necessarily provide for version numbers, but you can query information about the environment at interpretation time:
 
<langsyntaxhighlight lang="forth">s" MAX-U" environment? [IF]
0xffffffff <> [IF] .( Requires 32 bits! ) bye [THEN]
[THEN]
Line 587 ⟶ 618:
[defined] abs [if]
bloop @ abs
[then] [then]</langsyntaxhighlight>
[[4tH]] is able to fulfill all requirements. Note that since only one variable has been declared, the sum of all integer (user)variables is consequently the value of that variable.
{{Works with|4tH|3.62.2}}
<langsyntaxhighlight lang="forth">[hex] 362 [decimal] 4TH# - [if] [abort] [then]
 
-32 value bloop
Line 600 ⟶ 631:
 
0 last cell+ first over over - .( User variables: ) .
?do i @ + loop .( Sum: ) . cr</langsyntaxhighlight>
{{out}}
<pre>
Line 609 ⟶ 640:
=={{header|FreeBASIC}}==
Version 1:
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
#If __FB_VERSION__ < "1.06.0"
Line 625 ⟶ 656:
Print "bloop does not exist"
#EndIf
Sleep</langsyntaxhighlight>
{{out}}
<pre>introspection.bas(4) error: Compiler version is too old - needs to be 1.06.0 or later</pre>
Version 2:
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
#If __FB_VERSION__ < "1.05.0" '' version 1.05.0 is now OK
Line 645 ⟶ 676:
Print "bloop does not exist"
#EndIf
Sleep</langsyntaxhighlight>
{{out}}
<pre>Abs(bloop) = 15</pre>
Version 3 (version code omitted for brevity):
<langsyntaxhighlight lang="freebasic">#Undef Abs '' undefine Abs keyword
Dim bloop As Integer = -15
#IfDef bloop
Line 660 ⟶ 691:
Print "bloop does not exist"
#EndIf
Sleep</langsyntaxhighlight>
{{out}}
<pre>Abs is not available</pre>
Version 4 (version code omitted for brevity):
<langsyntaxhighlight lang="freebasic">#Undef Abs '' undefine Abs keyword
'Dim bloop As Integer = -15 '' bloop declaration commented out
#IfDef bloop
Line 675 ⟶ 706:
Print "bloop does not exist"
#EndIf
Sleep</langsyntaxhighlight>
{{out}}
<pre>bloop does not exist</pre>
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">if FrinkVersion[] < "2024-01-01"
{
println["Version of Frink is too old."]
exit[]
}
 
if isVariableDefined["bloop"]
{
func = getFunction["abs",1]
if func != undef
println[func[bloop]]
}</syntaxhighlight>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># Apply a function to a value, given variable names for both function and value
CheckEval := function(fun, val)
local f, x;
Line 709 ⟶ 754:
od;
return s;
end;</langsyntaxhighlight>
 
=={{header|Go}}==
Task variance: "exit if it is too old" is not done here. Go version strings do not present an easily interpreted chronology. This version of the program simply prints the version string.
<langsyntaxhighlight lang="go">package main
 
import (
Line 771 ⟶ 816:
fmt.Println(" abs(bloop): ", math.Abs(bloop))
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 786 ⟶ 831:
=={{header|Haskell}}==
 
<langsyntaxhighlight lang="haskell">import Data.Version
import Control.Monad
import System.Info
Line 793 ⟶ 838:
 
main = when (compilerName == "ghc" && compilerVersion < minGHCVersion) $
fail "Compiler too old."</langsyntaxhighlight>
 
No means exists of checking whether a variable exists at runtime. The set of variables that exist in any given scope is fixed at compile-time.
Line 799 ⟶ 844:
=={{header|Icon}} and {{header|Unicon}}==
 
<langsyntaxhighlight lang="unicon">global bloop
 
procedure main(A)
Line 816 ⟶ 861:
return (major < maj) | ((major = maj) & (minor < min))
}
end</langsyntaxhighlight>
Sample run:
<pre>->introspect
Line 825 ⟶ 870:
=={{header|Inform 7}}==
Inform 7 doesn't have built-in functionality for checking the runtime version number, but the version number is available and can be read by including a snippet of Inform 6 code. The address and format of the version number vary according to the virtual machine being targeted.
<langsyntaxhighlight lang="inform7">Home is a room.
 
When play begins:
Line 849 ⟶ 894:
 
To decide which version is current runtime version: (- ($32-->0) -).
To decide which version is required runtime version: decide on 1.1.</langsyntaxhighlight>
 
It's not possible to check for the existence of functions (invoking a nonexistent phrase causes a compile-time error) or list global variables.
 
=={{header|Io}}==
<langsyntaxhighlight lang="io">if(System version < 20080000, exit)
 
if(hasSlot("bloop") and bloop hasSlot("abs"), bloop abs)</langsyntaxhighlight>
 
Io can also inspect the source code of methods written in Io:
<langsyntaxhighlight lang="io">getSlot("arbitraryMethod") code</langsyntaxhighlight>
 
=={{header|IS-BASIC}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 IF VERNUM<2.1 THEN PRINT "Version is too old.":STOP
110 WHEN EXCEPTION USE ERROR
120 PRINT ABS(BLOOP)
Line 869 ⟶ 914:
150 PRINT EXSTRING$(EXTYPE)
160 CONTINUE
170 END HANDLER</langsyntaxhighlight>
 
=={{header|J}}==
Exit if we're running an old version of J (earlier than version 6, which is current as of this writing), giving version number as the exit status:
<langsyntaxhighlight lang="j">6 (2!:55@:]^:>) 0 ". 1 { 9!:14''</langsyntaxhighlight>
Compute <tt>abs(bloop)</tt> if <tt>abs</tt> is a function and <tt>bloop</tt> is data:
<langsyntaxhighlight lang="j">".(#~3 0*./ .=4!:0@;:)'abs bloop'</langsyntaxhighlight>
'''Extra credit''': report the number of integer variables in global scope, and their sum:
<langsyntaxhighlight lang="j">((],&(+/);@#~)((=<.)@[^:](''-:$)*.0=0{.@#,)&>)".&.>4!:1]0</langsyntaxhighlight>
 
This last expression is longer than the others, because it has a couple of extra guard checks; in J, the programmer doesn't need to care if the data is a single number or an array, or what hardware representation is used for numbers (32-bit int, IEEE float, etc).
Line 885 ⟶ 930:
=={{header|Java}}==
You can't see if a variable or function is available in Java (it will be a compile time error if you try to use them when you they aren't available), but you can check the version number using the <tt>System</tt> class:
<langsyntaxhighlight lang="java">public class VersCheck {
public static void main(String[] args) {
String vers = System.getProperty("java.version");
Line 896 ⟶ 941:
}
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 904 ⟶ 949:
Testing whether the variable “bloop” exists:
 
<langsyntaxhighlight lang="javascript">if (typeof bloop !== "undefined") { ... }</langsyntaxhighlight>
 
The <code>typeof</code> operator explicitly does not throw an error when given an undeclared variable.
Line 910 ⟶ 955:
Test whether <code>Math.abs()</code> is available:
 
<langsyntaxhighlight lang="javascript">if ("abs" in Math) { ... }</langsyntaxhighlight>
 
<code>abs</code> is a method of the Math object, methods are properties, and the <code>in</code> operator tests whether an object has the named property.
 
=={{header|Juliajq}}==
jq's powers of introspection are currently very limited, being
{{works with|Julia|0.6}}
essentially confined to the built-in function `builtins`, which
as the name suggests only yields information about built-in filters (name and arity).
 
Version information can however be made available to a running jq program as illustrated here:
<lang julia>@show VERSION
 
jq --arg version $(jq --version) '$version'
 
References to undefined functions and undefined variables (that is jq's "$-variables")
are regarded as errors that cannot be caught, but in a pinch one can use the
technique illustrated here:
 
jq -n --argjson bloop null 'if $bloop then $bloop|length else "undefined" end'
 
As it happens, jq's "abs" function is named "length" (don't ask why),
so the task regarding `abs()` cannot really be accomplished using the name `abs`.
 
=={{header|Jsish}}==
<syntaxhighlight lang="javascript">/* Introspection, in jsish */
if (Info.version() < Util.verConvert('2.8.6')) {
puts("need at least version 2.8.6 of jsish for this application");
exit(1);
}
 
/* Check for "abs()" as function and "bloop" as defined value, call if both check true */
if ((bloop != undefined) && (typeof Math.abs == 'function')) {
puts(Math.abs(bloop));
}
 
/* ECMAScript, this will sum all numeric values, not just strict integers */
var nums = 0, sums = 0, v;
for (v of Info.vars(this)) {
if (isFinite(this[v])) {
nums++;
sums += this[v];
}
}
printf("%d numerics with sum of: %d\n", nums, sums);</syntaxhighlight>
 
{{out}}
<pre>prompt$ jsish introspection.jsi
2 numerics with sum of: 2</pre>
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">@show VERSION
VERSION < v"0.4" && exit(1)
 
if isdefined(Base, :bloop) && !isempty(methods(abs))
@show abs(bloop)
end
Line 927 ⟶ 1,014:
vars = filter(x -> eval(x) isa Integer, names(Main))
println("Integer variables: ", join(vars, ", "), ".")
println("Sum of integers in the global scope: ", sum(eval.(vars)), ".")</langsyntaxhighlight>
 
{{out}}
<pre>VERSION = v"0.61.2.0"
Integer variables: a, b, c.
Sum of integers in the global scope: 6.</pre>
Line 936 ⟶ 1,023:
=={{header|Kotlin}}==
We will use Java reflection for this task as Kotlin's own reflection facilities do not appear to be able to deal generically with top-level entities at the present time (i.e. ::class isn't yet supported):
<langsyntaxhighlight lang="scala">// version 1.0.6 (intro.kt)
 
import java.lang.reflect.Method
Line 975 ⟶ 1,062:
}
println("\nThere are $count global integer variables and their sum is $sum")
}</langsyntaxhighlight>
 
{{out}}
Line 987 ⟶ 1,074:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">var(bloob = -26)
 
decimal(lasso_version(-lassoversion)) < 9.2 ? abort
 
var_defined('bloob') and $bloob -> isa(::integer) and lasso_tagexists('math_abs') ? math_abs($bloob)</langsyntaxhighlight>
-> 26
 
Lassos equivalence of global variables are thread variables. They have scope that lasts for the entire call in contrast to local variables that are confined to the page or method they are created within.
 
<langsyntaxhighlight Lassolang="lasso">var(
bloob = -26,
positive = 450
Line 1,010 ⟶ 1,097:
}
 
#total</langsyntaxhighlight>
-> 424
 
=={{header|Lingo}}==
*verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old.
<langsyntaxhighlight lang="lingo">put _player.productVersion
-- "11.5.9"
 
_player.itemDelimiter="."
if integer(_player.productVersion.item[1])<11 then _player.quit()</langsyntaxhighlight>
 
*check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop).
<langsyntaxhighlight lang="lingo">-- check existanceexistence of bloop in local scope
bloopExists = not voidP(value("bloop"))
-- or for global scope:
-- bloopExists = not voidP(_global.bloop)
absExists = value("abs(1)")=1
if bloopExists and absExists then put abs(bloop) -- or abs(_global.bloop)</langsyntaxhighlight>
 
*Report the number of integer variables in global scope, and their sum.
<langsyntaxhighlight lang="lingo">cnt = 0
sum = 0
repeat with v in the globals
Line 1,039 ⟶ 1,126:
end repeat
put cnt
put sum</langsyntaxhighlight>
 
=={{header|Locomotive Basic}}==
Line 1,045 ⟶ 1,132:
To get the BASIC ROM version number, we need to use a Z80 machine code routine which copies the version number (major/minor/patchlevel) to RAM where BASIC can then read it. Here is the assembly:
 
<langsyntaxhighlight lang="z80">org &4000 ; program start address
 
push bc
Line 1,068 ⟶ 1,155:
pop de
pop bc
ret</langsyntaxhighlight>
 
The following BASIC program POKEs that routine into memory and quits prematurely if BASIC 1.0 is detected (meaning the machine is a CPC464), as opposed to the more standard 1.1 or later:
 
<langsyntaxhighlight lang="locobasic">10 s=&4000:SYMBOL AFTER 256:MEMORY s-1
20 FOR i=0 to 34:READ a:POKE s+i,a:NEXT
30 DATA &c5,&d5,&e5,&f5,&01,&00,&df,&ed,&49,&01,&86,&7f,&ed,&49
Line 1,080 ⟶ 1,167:
70 PRINT "BASIC ROM version is ";PEEK(&4040);".";PEEK(&4041);".";PEEK(&4042)
80 IF PEEK(&4041)=0 THEN PRINT "Uh oh, you are still using BASIC 1.0":END
90 PRINT "You are using BASIC 1.1 or later, program can continue"</langsyntaxhighlight>
 
The second subtask, testing for the presence of a variable, is done here by trying to get the memory address of the variable. If that fails, it is obviously is not yet defined:
 
<langsyntaxhighlight lang="locobasic">1 ' decide randomly whether to define the variable:
10 IF RND>.5 THEN bloop=-100*RND
20 ON ERROR GOTO 100
Line 1,091 ⟶ 1,178:
50 PRINT "ABS of bloop is",ABS(bloop)
90 END
100 IF ERL=30 THEN PRINT "Variable bloop not defined":RESUME 90</langsyntaxhighlight>
 
(Like the Spectrum version, we have omitted checking for ABS because it is a builit-in function of the BASIC interpreter and therefore always present.)
Line 1,097 ⟶ 1,184:
'''Extra credit''': Finally, we can traverse the memory area where BASIC stores its integer, real, and string variables and add together all integers (type 1):
 
<langsyntaxhighlight lang="locobasic">10 ' The program should find and add those three integers (%), ignoring reals:
20 foo%=-4:bar%=7:baz%=9:somereal=3.141
30 varstart=&ae68 ' for CPC 664 and 6128
Line 1,114 ⟶ 1,201:
160 WEND
170 PRINT "There are"num"integer variables."
180 PRINT "Their sum is"sum</langsyntaxhighlight>
 
{{out}}
Line 1,122 ⟶ 1,209:
=={{header|Logo}}==
{{works with|UCB Logo}}
<langsyntaxhighlight lang="logo">show logoversion ; 5.6
if logoversion < 6.0 [print [too old!]]
 
if and [name? "a] [number? :a] [
print ifelse procedure? "abs [abs :a] [ifelse :a < 0 [minus :a] [:a]]
]</langsyntaxhighlight>
 
=={{header|Logtalk}}==
<langsyntaxhighlight lang="logtalk">
:- object(my_application).
 
Line 1,164 ⟶ 1,251:
 
:- end_object.
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">if _VERSION:sub(5) + 0 < 5.1 then print"too old" end --_VERSION is "Lua <version>".
 
if bloop and math.abs then print(math.abs(bloop)) end</langsyntaxhighlight>
 
=={{header|Maple}}==
The "version" kernel option returns a string similar to
<langsyntaxhighlight Maplelang="maple">> kernelopts( 'version' );
Maple 16.00, SUN SPARC SOLARIS, Mar 3 2012, Build ID 732982</langsyntaxhighlight>
The following does the trick for the first bit.
<langsyntaxhighlight Maplelang="maple">> if sscanf( (StringTools:-Split(kernelopts(version))[2]), "%d.%d" )[1] < 300 then `quit`(1) end;</langsyntaxhighlight>
(There is also an internal "version" procedure, which returns a build ID, but this is less obvious to use, as you'd need a table mapping versions to build IDs. Besides, it prints stuff.)
 
It doesn't really make sense to ask whether a variable "exists"; it springs into existence by uttering it in code. So I'll interpret the problem as asking whether it is assigned some kind of numeric value to which abs() can be applied.
<langsyntaxhighlight Maplelang="maple">> if type( bloop, complex( extended_numeric ) ) and type( abs, mathfunc ) then print( abs( bloop ) ) end:
1/2
13</langsyntaxhighlight>
Note that it is not necessary to check that the name "bloop" is assigned (though it is possible to do so), since an unassigned name is a first-class value in Maple. Another possible interpretation is that the symbolic expression
<langsyntaxhighlight Maplelang="maple">> abs( bloop );
| bloop |</langsyntaxhighlight>
is a perfectly good expression in Maple, so checking for the the "existence" of "bloop" isn't necessary in the first place. (One probably would not bother to check that abs() was actually there either, unless one expected that the standard library was broken.)
 
Here are the number and sum of the assigned integer globals in my current (fresh) session.
<langsyntaxhighlight Maplelang="maple">> nops([anames](integer));
3
 
> eval(`+`(anames(integer)));
17
</syntaxhighlight>
</lang>
If I change it, I get:
<syntaxhighlight lang="maple">
<lang Maple>
> foo := 25:
> nops([anames](integer));
Line 1,202 ⟶ 1,289:
 
> eval(`+`(anames(integer)));
42</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">If[$VersionNumber < 8, Quit[]]
If[NameQ["bloop"] && NameQ["Abs"],
Print[Abs[bloop]]]</langsyntaxhighlight>
 
{{out}}
<pre>7</pre>
 
<syntaxhighlight lang="text">globalintegers = Symbol /@ Select[Names["Global`*"], IntegerQ[Symbol[#]] &];
Print [ globalintegers //Length, " global integer(s) and their sum is: ", globalintegers // Total] </langsyntaxhighlight>
 
{{out}}
Line 1,219 ⟶ 1,306:
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight Matlablang="matlab"> % convert version into numerical value
v = version;
v(v=='.')=' ';
Line 1,239 ⟶ 1,326:
printf('abs(bloob) is %f\n',abs(bloob));
return;
end; </langsyntaxhighlight>
Extra credit task:
<syntaxhighlight lang="matlab">
<lang Matlab>
% find all integers
varlist = whos;
Line 1,257 ⟶ 1,344:
printf('sum of integer scalars: %i\n',intsum);
printf('sum of all integer elements: %i\n',intsumall);
</syntaxhighlight>
</lang>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">/* Get version information */
build_info();
/* build_info("5.27.0", "2012-05-08 11:27:57", "i686-pc-mingw32", "GNU Common Lisp (GCL)", "GCL 2.6.8") */
Line 1,277 ⟶ 1,364:
 
/* Sum of integer variables */
lreduce("+", sublist(map(ev, values), integerp));</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<langsyntaxhighlight lang="maxscript">fn computeAbsBloop bloop =
(
versionNumber = maxVersion()
Line 1,307 ⟶ 1,394:
)
 
computeAbsBloop -17</langsyntaxhighlight>
 
=={{header|NetRexx}}==
Line 1,313 ⟶ 1,400:
 
The language does however return a string identifying the version of NetRexx in effect when the current class was last processed. This information can be retrieved through the '''<tt>version</tt>''' ''special variable''.
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
 
Line 1,338 ⟶ 1,425:
end
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,349 ⟶ 1,436:
 
=={{header|Nim}}==
In Nim, many checks are done at compile time. So, you have the choice to emit an error or warning at compile time or exit at runtime.
<lang nim>echo NimVersion
<syntaxhighlight lang="nim">when NimVersion < "1.2":
error "This compiler is too old" # Error at compile time.
 
assert NimVersion >= "1.4", "This compiler is too old." # Assertion defect at runtime.
 
var bloop = -12
 
when compiles abs(bloop):
echo abs(bloop)</langsyntaxhighlight>
 
{{out}}
<pre>0.10.312</pre>
12</pre>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml"># Sys.ocaml_version;;
- : string = "3.10.2"</langsyntaxhighlight>
 
<langsyntaxhighlight lang="ocaml"># Scanf.sscanf (Sys.ocaml_version) "%d.%d.%d"
(fun major minor micro -> major, minor, micro) ;;
- : int * int * int = (3, 10, 2)</langsyntaxhighlight>
 
Checking if an identifier (a value or a function) is bound doesn't make any sens in OCaml, which is strongly staticaly typed.
Line 1,376 ⟶ 1,467:
Oforth does not have global variables, only global constants.
 
<langsyntaxhighlight Oforthlang="oforth">: bloopAbs
| bl m |
System.VERSION println
Line 1,387 ⟶ 1,478:
 
System.Out "bloop value is : " << bl value << cr
System.Out "bloop abs is : " << bl value m perform << cr ;</langsyntaxhighlight>
 
{{out}}
Line 1,403 ⟶ 1,494:
ok
</pre>
 
=={{header|OxygenBasic}}==
Compile time introspection
<syntaxhighlight lang="text">
 
$ rtlversion "0.4.0"
'
#if not match(rtlversion,o2version)
#error "This RTL version mismatches o2 version "+o2version
#else
print o2version
#endif
 
float bloop=-1618
 
#ifdef bloop
#ifdef abs
print abs(bloop)
#endif
#endif
</syntaxhighlight>
 
=={{header|Oz}}==
We cannot check whether a variable is in scope (static property).
We <em>can</em> check whether a module exports a certain value. However, for system modules the compiler will refuse to compile if we try to use a non-existing value.
<langsyntaxhighlight lang="oz">declare
Version = {Property.get 'oz.version'}
%% Version is an atom like '1.4.0'. So we can not compare it directly.
Line 1,420 ⟶ 1,532:
else
{System.showInfo "Your Mozart version is too old."}
end</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.4.3 and above}}
<langsyntaxhighlight lang="parigp">if(lex(version(), [2,4,3]) < 0, quit()); \\ Compare the version to 2.4.3 lexicographically
 
if(bloop!='bloop && type(abs) == "t_CLOSURE", abs(bloop))</langsyntaxhighlight>
 
=={{header|Perl}}==
{{works with|Perl|5.x}}
<langsyntaxhighlight lang="perl">require v5.6.1; # run time version check
require 5.6.1; # ditto
require 5.006_001; # ditto; preferred for backwards compatibility</langsyntaxhighlight>
 
To check if a variable exists, do a name lookup of it in the package symbol table:
<langsyntaxhighlight lang="perl">#$bloop = -123; # uncomment this line to see the difference
no strict 'refs'; # referring to variable by name goes against 'strict' pragma
if (defined($::{'bloop'})) {print abs(${'bloop'})} else {print "bloop isn't defined"};</langsyntaxhighlight>
 
To check if certain built-in function is available (maybe you are using a stripped down build of perl binary, for example), one can use eval, but make sure the statement you are eval'ing doesn't have side effect:
<langsyntaxhighlight lang="perl">eval('abs(0)'); # eval("") instead of eval{}; the latter is not for run-time check
print "abs() doesn't seem to be available\n" if $@;</langsyntaxhighlight>
 
To check if a package or object provides certain method name, use 'can':
<langsyntaxhighlight lang="perl">use Math::Complex;
my $cpl = Math::Complex->new(1,1);
 
Line 1,452 ⟶ 1,564:
print "object \$cpl does not have 'explode' method\n"
unless $cpl->can('explode');
</syntaxhighlight>
</lang>
Keep in mind that what a package has as method names are not equal to what method names can be called on this package, due to things like AUTOLOAD.
For most uses, introspection is meaningless, just call the method (and catch exceptions if it's important).
 
An example that solves the task:
<langsyntaxhighlight lang="perl">use 5.010;
our $bloop = -12;
if (defined $::bloop) {
Line 1,469 ⟶ 1,581:
else {
say '$bloop is not defined';
}</langsyntaxhighlight>
Note that this program will exit with a message "Perl v5.10.0 required" if run under perl version lower than 5.10 and it actually uses a feature introduced in that version (<code>say</code>).
The program checks whether the variable is actually defined and not if it just exists.
Line 1,477 ⟶ 1,589:
 
Extra task:
<langsyntaxhighlight lang="perl">use 5.010;
package test;
use Regexp::Common;
Line 1,492 ⟶ 1,604:
my $num = @ints;
my $sum = sum @ints;
say "$num integers, sum = $sum";</langsyntaxhighlight>
It prints:
<pre>
Line 1,499 ⟶ 1,611:
This example uses the <code>test</code> namespace instead of the default, because there already are some integer numbers in the <code>main</code> namespace like the PID, etc.
The program to sum those numbers would be:
<langsyntaxhighlight lang="perl">use 5.010;
use Regexp::Common;
use List::Util qw(sum);
Line 1,505 ⟶ 1,617:
my $num = @ints;
my $sum = sum @ints;
say "$num integers, sum = $sum";</langsyntaxhighlight>
<pre>
4 integers, sum = 74717
</pre>
 
=={{header|Perl 6Phix}}==
The requires procedure behaves like a compiler directive, although it is in fact just a normal executable routine.
<lang perl6>use v6; # require Perl 6
 
<!--<syntaxhighlight lang="phix">-->
my $bloop = -123;
<span style="color: #7060A8;">requires<span style="color: #0000FF;">(<span style="color: #008000;">"0.8.2"<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- crashes on 0.8.1 and earlier </span>
<span style="color: #7060A8;">requires<span style="color: #0000FF;">(<span style="color: #000000;">WINDOWS<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- crashes on Linux </span>
<span style="color: #7060A8;">requires<span style="color: #0000FF;">(<span style="color: #000000;">64<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- crashes on 32-bit
<!--</syntaxhighlight>-->
 
If passed a string it compares it (intelligently) against the interpreter/compiler version and terminates in error with a suitable message should it be too old to cope. Otherwise the parameter must be an integer: <32 checks the platform, >=32 checks the word size. In the latter case when (interpreting and) it needs to, it hunts for a suitable alternative runtime and offers to re-run with that, maybe you need bigger ints, or maybe you only ship a 32-bit libcurl.dll.
if MY::{'$bloop'}.defined and CORE::{'&abs'}.defined { say abs $bloop }
 
The version() routine used by the above can also be called directly and returns a string:
 
<!--<syntaxhighlight lang="phix">-->
<span style="color: #0000FF;">?<span style="color: #7060A8;">version<span style="color: #0000FF;">(<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- eg "0.8.0"
<!--</syntaxhighlight>-->
 
Normally only really useful for display, but you can of course break that down into an integer triplet with scanf(), as requires does, maybe something works on 0.7.7 and 0.7.9 but not 0.7.8.
 
Phix has a builtin abs() routine, which will be auto-included if referenced.
 
<!--<syntaxhighlight lang="phix">-->
<span style="color: #000080;font-style:italic;">--include pmaths.e -- (an auto-include, ok but not needed)
--include complex.e -- (not an auto-include, needed if used)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">r_abs</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">routine_id<span style="color: #0000FF;">(<span style="color: #008000;">"abs"<span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">--integer r_abs = routine_id("complex_abs")</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">r_abs<span style="color: #0000FF;">!=<span style="color: #0000FF;">-<span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
<span style="color: #0000FF;">?<span style="color: #7060A8;">call_func<span style="color: #0000FF;">(<span style="color: #000000;">r_abs<span style="color: #0000FF;">,<span style="color: #0000FF;">{<span style="color: #0000FF;">-<span style="color: #000000;">42<span style="color: #0000FF;">}<span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if
<!--</syntaxhighlight>-->
Using complex_abs() is probably closer to the task requirement in that if complex.e is not included it will not be found/called.<br>
In this case it happens to give exactly the same result, however under the hood it is first promoting the -42 to -42+0i before returning sqrt((-42)*(-42)+(0)*(0)).
 
There is (as yet) no var_id() builtin, the following is a quick cobbling-together of code from builtins\VM\prtnidN.e (routine_id)
and builtins\VM\pDiagN.e (ex.err file creation), not very pretty but it seems to work, and of course all this sort of stuff is
normally hidden away out of sight in builtins\VM.
 
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins<span style="color: #0000FF;">/<span style="color: #000000;">VM<span style="color: #0000FF;">/<span style="color: #000000;">pStack<span style="color: #0000FF;">.<span style="color: #000000;">e</span> <span style="color: #000080;font-style:italic;">-- :%opGetST
-- copies from pglobals.e:</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">S_Name</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1<span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- const/var/rtn name</span>
<span style="color: #000000;">S_NTyp</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">2<span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- Const/GVar/TVar/Nspc/Type/Func/Proc</span>
<span style="color: #000000;">S_FPno</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">3<span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- File and Path number</span>
<span style="color: #000000;">S_Slink</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">6<span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- scope/secondary chain (see below)</span>
<span style="color: #000000;">S_vtype</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">7<span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- variable type or namespace fileno</span>
<span style="color: #000000;">S_GVar2</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">2<span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- global or static variable</span>
<span style="color: #000000;">T_int</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1<span style="color: #0000FF;">,</span>
<span style="color: #000000;">T_EBP</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">22<span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- compiled/listing=0, interpreted={ebp4,esp4,sym4} (set at last possible moment)</span>
<span style="color: #000000;">T_ds4</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">23</span> <span style="color: #000080;font-style:italic;">-- compiled = start of data section, same but /4 when interpreted ([T_EBP]!=0)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">var_id<span style="color: #0000FF;">(<span style="color: #004080;">object</span> <span style="color: #000000;">s<span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- hacked copy of routine_id(), for local file-level integers only</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">res<span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- symidx for string s, else sum(local gvar integers)</span>
<span style="color: #000000;">rtn<span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- routine number of callee, from callstack</span>
<span style="color: #000000;">cFno<span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- calling fileno.</span>
<span style="color: #000000;">tidx<span style="color: #0000FF;">,</span>
<span style="color: #000000;">ds4</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">symtab<span style="color: #0000FF;">,</span>
<span style="color: #000000;">si<span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- copy of symtab[i], speedwise</span>
<span style="color: #000000;">si_name</span> <span style="color: #000080;font-style:italic;">-- copy of symtab[i][S_name], speedwise/thread-sfaety
-- get copy of symtab. NB read only! may contain nuts! (unassigned vars)</span>
<span style="color: #000000;">enter_cs<span style="color: #0000FF;">(<span style="color: #0000FF;">)</span>
<span style="color: #000000;"> #ilASM{
[32]
lea edi,[symtab]
call :%opGetST -- [edi]=symtab (ie our local:=the real symtab)
mov edi,[ebp+20] -- prev_ebp
mov edi,[edi+8] -- calling routine no
mov [rtn],edi
[64]
lea rdi,[symtab]
call :%opGetST -- [rdi]=symtab (ie our local:=the real symtab)
mov rdi,[rbp+40] -- prev_ebp
mov rdi,[rdi+16] -- calling routine no
mov [rtn],rdi
[]
}</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">symtab<span style="color: #0000FF;">[<span style="color: #000000;">T_EBP<span style="color: #0000FF;">]<span style="color: #0000FF;">=<span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #000080;font-style:italic;">-- compiled</span>
<span style="color: #000000;">ds4</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor<span style="color: #0000FF;">(<span style="color: #000000;">symtab<span style="color: #0000FF;">[<span style="color: #000000;">T_ds4<span style="color: #0000FF;">]<span style="color: #0000FF;">/<span style="color: #000000;">4<span style="color: #0000FF;">)</span>
<span style="color: #008080;">else</span> <span style="color: #000080;font-style:italic;">-- interpreted</span>
<span style="color: #000000;">ds4</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">symtab<span style="color: #0000FF;">[<span style="color: #000000;">T_ds4<span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">cFno</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">symtab<span style="color: #0000FF;">[<span style="color: #000000;">rtn<span style="color: #0000FF;">]<span style="color: #0000FF;">[<span style="color: #000000;">S_FPno<span style="color: #0000FF;">]</span> <span style="color: #000080;font-style:italic;">-- fileno of callee (whether routine or toplevel)</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff<span style="color: #0000FF;">(<span style="color: #000000;">s<span style="color: #0000FF;">=<span style="color: #000000;">0<span style="color: #0000FF;">?<span style="color: #000000;">0<span style="color: #0000FF;">:<span style="color: #0000FF;">-<span style="color: #000000;">1<span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i<span style="color: #0000FF;">=<span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length<span style="color: #0000FF;">(<span style="color: #000000;">symtab<span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">si</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">symtab<span style="color: #0000FF;">[<span style="color: #000000;">i<span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #004080;">sequence<span style="color: #0000FF;">(<span style="color: #000000;">si<span style="color: #0000FF;">)</span>
<span style="color: #008080;">and</span> <span style="color: #000000;">si<span style="color: #0000FF;">[<span style="color: #000000;">S_NTyp<span style="color: #0000FF;">]<span style="color: #0000FF;">=<span style="color: #000000;">S_GVar2</span>
<span style="color: #008080;">and</span> <span style="color: #000000;">si<span style="color: #0000FF;">[<span style="color: #000000;">S_FPno<span style="color: #0000FF;">]<span style="color: #0000FF;">=<span style="color: #000000;">cFno</span>
<span style="color: #008080;">and</span> <span style="color: #000000;">si<span style="color: #0000FF;">[<span style="color: #000000;">S_vtype<span style="color: #0000FF;">]<span style="color: #0000FF;">=<span style="color: #000000;">T_int</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">si_name</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">si<span style="color: #0000FF;">[<span style="color: #000000;">S_Name<span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">s<span style="color: #0000FF;">=<span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #000080;font-style:italic;">-- cut-down version of pDiagN.e/getGvarValue():</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">gidx</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">si<span style="color: #0000FF;">[<span style="color: #000000;">S_Slink<span style="color: #0000FF;">]<span style="color: #0000FF;">,</span> <span style="color: #000000;">novalue<span style="color: #0000FF;">,</span> <span style="color: #000000;">o</span>
#ilASM{
mov [novalue],0
[32]
mov esi,[ds4]
mov edx,[gidx]
shl esi,2
mov esi,[esi+edx*4+16] -- ([ds+(gidx+4)*4] == gvar[gidx])
cmp esi,h4
jl @f
mov [novalue],1
xor esi,esi
@@:
mov [o],esi
[64]
mov rsi,[ds4]
mov rdx,[gidx]
shl rsi,2
mov rsi,[rsi+rdx*8+24] -- ([ds+(gidx+3)*8] == gvar[gidx])
mov r15,h4
cmp rsi,r15
jl @f
mov [novalue],1
xor rsi,rsi
@@:
mov [o],rsi
[]
}
<span style="color: #008080;">if</span> <span style="color: #000000;">novalue</span> <span style="color: #008080;">then</span>
<span style="color: #0000FF;">?<span style="color: #0000FF;">{<span style="color: #000000;">si_name<span style="color: #0000FF;">,<span style="color: #008000;">"no_value"<span style="color: #0000FF;">}</span>
<span style="color: #008080;">else</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">o</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">elsif</span> <span style="color: #000000;">s<span style="color: #0000FF;">=<span style="color: #000000;">si_name</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">i</span>
<span style="color: #008080;">exit</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000000;">si_name</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #000000;">si</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #000000;">symtab</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #000000;">leave_cs<span style="color: #0000FF;">(<span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #0000FF;">{<span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">routine_id<span style="color: #0000FF;">(<span style="color: #008000;">"blurgzmp"<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- force symtab name population..
-- (alt: see rbldrqd in pDiagN.e)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">bloop</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">5<span style="color: #0000FF;">,</span>
<span style="color: #000080;font-style:italic;">-- barf, -- triggers {"barf","no_value"}</span>
<span style="color: #000000;">burp</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">35</span>
<span style="color: #000000;">bloop</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">6</span>
<span style="color: #000000;">burp</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #0000FF;">?<span style="color: #000000;">var_id<span style="color: #0000FF;">(<span style="color: #008000;">"bloop"<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- >0 === exists</span>
<span style="color: #0000FF;">?<span style="color: #000000;">var_id<span style="color: #0000FF;">(<span style="color: #008000;">"blooop"<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- -1 === does not exist</span>
<span style="color: #0000FF;">?<span style="color: #000000;">var_id<span style="color: #0000FF;">(<span style="color: #000000;">0<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- bloop+burp = 42</span>
<span style="color: #0000FF;">?<span style="color: #000000;">bloop<span style="color: #0000FF;">+<span style="color: #000000;">burp</span> <span style="color: #000080;font-style:italic;">-- "", doh
<!--</syntaxhighlight>-->
 
my @ints = ($_ when Int for PROCESS::.values);
say "Number of PROCESS vars of type Int: ", +@ints;
say "PROCESS vars of type Int add up to ", [+] @ints;</lang>
{{out}}
<pre>123
1257
Number of PROCESS vars of type Int: 1
-1
PROCESS vars of type Int add up to 28785</pre>
42
Obviously Perl 6 doesn't maintain a lot of global integer variables... <tt>:-)</tt>
42
</pre>
As-is, of course, being integer-only-and-no-routine-level-vars, the above represents very limited practical value.
 
Other routines of interest include
Nevertheless, you can use similar code to access all the variables in any package you like,
 
such as the GLOBAL package, which typically has absolutely nothing in it. Since the PROCESS package is even more global than GLOBAL, we used that instead. Go figure...
<!--<syntaxhighlight lang="phix">-->
<span style="color: #0000FF;">?<span style="color: #7060A8;">platform<span style="color: #0000FF;">(<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- WINDOWS=2, LINUX=3</span>
<span style="color: #0000FF;">?<span style="color: #7060A8;">machine_bits<span style="color: #0000FF;">(<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 32 or 64</span>
<span style="color: #0000FF;">?<span style="color: #7060A8;">machine_word<span style="color: #0000FF;">(<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 4 or 8</span>
<span style="color: #0000FF;">?<span style="color: #7060A8;">include_paths<span style="color: #0000FF;">(<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- eg {"C:\\Program Files (x86)\\Phix\\builtins\\",
-- "C:\\Program Files (x86)\\Phix\\builtins\\VM\\",
-- "C:\\Program Files (x86)\\Phix\\"}
-- (plus other application-specific directories)</span>
<span style="color: #0000FF;">?<span style="color: #7060A8;">get_interpreter<span style="color: #0000FF;">(<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- eg "C:\Program Files (x86)\Phix\p.exe"
-- or perhaps "/home/pete/phix/p" on Linux
<!--</syntaxhighlight>-->
 
Phix supports the absolute bare minimum use of #ifdef, for compatibility with OpenEuphoria, however it is almost always better
to use platform() and friends as normal hll code, rather than that sort of language-within-a-language stuff, imnsho, and the
compiler is pretty good at optimising away most such os-specific tests and whole branches of irrelevant code (see EmitON=0).
 
=={{header|Phixmonti}}==
<syntaxhighlight lang="phixmonti">_version 1.0 < if "Interpreter version is old" else "Last version" endif print</syntaxhighlight>
The program will not be executed if the variable or function has not been defined.
 
=={{header|PHP}}==
 
<langsyntaxhighlight lang="php"><?php
 
if (version_compare(PHP_VERSION, '5.3.0', '<' ))
Line 1,546 ⟶ 1,823:
echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n");
 
?></langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(unless (>= (version T) (3 0 1)) # Check version (only in the 64-bit version)
(bye) )
 
Line 1,557 ⟶ 1,834:
(num? bloop) # When 'bloop' is bound to a number
(getd 'abs) # and 'abs' defined as a function
(println (abs bloop)) ) # then print the absolute value</langsyntaxhighlight>
 
=={{header|PL/I}}==
===Version 1===
<syntaxhighlight lang="pl/i">
<lang PL/I>
S = SYSVERSION();
if substr(S, 6, 6) < '050000' then
do; put skip list ('Version of compiler is too old'); stop; end;
</syntaxhighlight>
</lang>
===Version 2===
<langsyntaxhighlight PLlang="pl/Ii">*process source attributes options m or(!);
/*********************************************************************
* 02-11.2013 Walter Pachl
Line 1,588 ⟶ 1,865:
Else
Put Skip List('Version is '!!s);
End</langsyntaxhighlight>
{{out}}
<pre>Version is PL/I for Win* 7.5</pre>
Line 1,595 ⟶ 1,872:
Variable pop_internal_version contains Poplog version in numeric form (as an integer) -- this one is most convenient for version checks. For printing one can use pop_version (which is a string containing more information).
 
<langsyntaxhighlight lang="pop11">;;; Exit if version below 15.00
if pop_internal_version < 150000 then
sysexit()
endif;</langsyntaxhighlight>
 
Pop11 variables are named by words. Pop11 word is a unique version of string stored in dictionary. So we need first convert strings to words and then query about words. Pop11 variables can store any value including functions and in fact when one accesses a function like abs by name one merely access a variable abs which happen to hold predefined function abs. To follow spirit of the task as closely as possible we check if abs indeed holds functional value.
 
<langsyntaxhighlight lang="pop11">;;; We do main task in a procedure
define check_and_call(x, y);
lvars wx=consword(x), wy=consword(y);
Line 1,618 ⟶ 1,895:
vars bloop = -5;
;;; Now prints 5
check_and_call('abs' , 'bloop') =></langsyntaxhighlight>
 
Note that here bloop is defined as "permanent" variable, Pop11 also have lexical variables which are not available for introspection.
Line 1,628 ⟶ 1,905:
The compiler directive <code>#COMPILER</code>, introduced with PB/Win 8 and PB/CC <!--uncertain version here--> 4, will fail the compile if the compiler does not match at least one of the listed compilers, and is not at least the (optional) minimum version of that compiler.
 
<langsyntaxhighlight lang="powerbasic">#COMPILER PBWIN 9
#COMPILER PBWIN, PBCC 5</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell"># version is found in $PSVersionTable
if ($PSVersionTable['PSVersion'] -lt '2.0') {
exit
Line 1,645 ⟶ 1,922:
| Where-Object { $_.Value -is [int] } `
| Measure-Object -Sum Value `
| Select-Object Count,Sum</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">CompilerIf #PB_Compiler_Version<441
CompilerError "You failed the version check!"
CompilerEndIf
Line 1,656 ⟶ 1,933:
Abs(bloop)
CompilerEndIf
CompilerEndIf</langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python"># Checking for system version
import sys
major, minor, bugfix = sys.version_info[:3]
Line 1,680 ⟶ 1,957:
 
if defined2('bloop') and defined2('abs') and callable(abs):
print abs(bloop)</langsyntaxhighlight>
You can combine both tests, (But loose sight of which variable in missing/not callable by wrapping the whole function call in a try-except statement:
<langsyntaxhighlight lang="python">try:
print abs(bloop)
except (NameError, TypeError):
print "Something's missing"</langsyntaxhighlight>
Here is one way to print the sum of all the global integer variables:
<langsyntaxhighlight lang="python">def sum_of_global_int_vars():
variables = vars(__builtins__).copy()
variables.update(globals())
print sum(v for v in variables.itervalues() if type(v) == int)
 
sum_of_global_int_vars()</langsyntaxhighlight>
 
=={{header|R}}==
{{works with|R|2.14.1}}
<syntaxhighlight lang="r">
<lang R>
if(getRversion() < "2.14.1")
{
warning("Your version of R is older than 2.14.1")
q() # exit R, with the option to cancel
}</langsyntaxhighlight>
The constants <code>version</code> and <code>R.version</code> give further information about the version that is running. The function <code>R.Version()</code> provides the same information as a list.
 
We now perform three checks: we want to know if bloop is in the user workspace (global environment), if abs exists somewhere, and if abs is a function.
<langsyntaxhighlight Rlang="r">bloop <- -3.4
if(exists("bloop", envir=globalenv()) && exists("abs") && is.function(abs))
{
abs(bloop)
}</langsyntaxhighlight>
Finally, we count how many integers are in the user workspace, and find their total. Note that a number followed by the letter L is considered to be an integer. See [[Integer_literals#R]] for more information.
<langsyntaxhighlight Rlang="r">#Declare some integers
qqq <- 45L
www <- -3L
Line 1,725 ⟶ 2,002:
the_ints <- mget(varnames[is_int], globalenv())
#Add them up
sum(unlist(the_ints))</langsyntaxhighlight>
 
=={{header|Racket}}==
 
The usual hack:
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
(unless (string<=? "5.3" (version)) (error "ancient version"))
</syntaxhighlight>
</lang>
 
Proper comparison:
<syntaxhighlight lang="racket">
<lang Racket>
(require version/utils)
(unless (version<=? "5.3" (version)) (error "ancient version"))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>my $bloop = -123;
 
if MY::{'$bloop'}.defined and CORE::{'&abs'}.defined { say abs $bloop }
 
my @ints = ($_ when Int for PROCESS::.values);
say "Number of PROCESS vars of type Int: ", +@ints;
say "PROCESS vars of type Int add up to ", [+] @ints;</syntaxhighlight>
{{out}}
<pre>123
Number of PROCESS vars of type Int: 1
PROCESS vars of type Int add up to 28785</pre>
Obviously Raku doesn't maintain a lot of global integer variables... <tt>:-)</tt>
 
Nevertheless, you can use similar code to access all the variables in any package you like,
such as the GLOBAL package, which typically has absolutely nothing in it. Since the PROCESS package is even more global than GLOBAL, we used that instead. Go figure...
 
=={{header|Raven}}==
<langsyntaxhighlight lang="raven">VERSION 0 prefer 20071104 <
if 'version >= 20071104 required' print bye
 
'bloop' GLOBAL keys in && 'abs' CORE keys in
if bloop abs print</langsyntaxhighlight>
 
 
=={{header|Retro}}==
This will exit if the minor version is less than 32019.6:
 
<lang Retro>version ^strings'splitAtChar: . drop toNumber 3 < &bye ifTrue</lang>
 
<syntaxhighlight lang="retro">@Version #201906 lt+ &bye if</syntaxhighlight>
A better way is to check the build number. This will exit if the build is lower than
the 11.0 release:
 
The existence of functions can be checked using '''d:lookup'''. In this, a helper function is provided to improve readability.
<lang Retro>build toNumber 1309798464 < &bye ifTrue</lang>
 
<syntaxhighlight lang="retro">
The existance of functions can be checked using find. In this, a helper function is provided to improve readability.
Checks for existence of "bloop" and "n:abs"
 
~~~
<lang Retro>
: executeByName (s-)
( Checks for existance of "bloop" and "abs" )
d:lookup [ d:xt fetch ] [ d:class fetch ] bi call ;
: executeByName ( $- )
find drop [ @d->xt ] [ @d->class ] bi withClass ;
 
"'bloop" "'n:abs" [ find nip ] bi@ and
[ "'bloop" executeByName "'n:abs" executeByName ] ifTrue</lang>if
~~~</syntaxhighlight>
 
Retro has no direct way to check for data types of functions. Assuming that a word class is defined for integer variables, we could do something like this:
 
<syntaxhighlight lang="retro">
<lang Retro>
#0 #0 last [ dup @d->:class fetch &.class:integer =eq? [ @d->:xt @fetch + [ 1+n:inc ] dip ] [ drop ] ifchoose ] ^types'LIST d:for-each@
</syntaxhighlight>
</lang>
 
After execution the stack will have the number of variables found, and the accumulated sum of their values.
Line 1,779 ⟶ 2,071:
=={{header|REXX}}==
Test to see if the version is at least version 4.
<langsyntaxhighlight lang="rexx"> /*output from parse version (almost all REXX versions) */
/* theREXXinterpreterName level mm Mon yyyy */
parse version . level .
if level<4 then exit</langsyntaxhighlight>
Test to see if the version is at least version 4, another example.
<langsyntaxhighlight lang="rexx">parse version x 1 whatLang level dd mon yyyy .
if level<4 then do
say
Line 1,790 ⟶ 2,082:
say x /*this displays everything.*/
exit /*or maybe: EXIT 13 */
end</langsyntaxhighlight>
Test to see if the REXX variable "bloop" exists, version 1.
<langsyntaxhighlight lang="rexx">if symbol('bloop')=='VAR' then say 'the "bloop" variable exists.'</langsyntaxhighlight>
Test to see if the REXX variable "bloop" exists, version 2.
<langsyntaxhighlight lang="rexx">if symbol('bloop')=='VAR' then say 'the "bloop" variable exists.'
else say 'the "bloop" variable doesn''t exist.'</langsyntaxhighlight>
Programming note: &nbsp; note the use of the double apostrophe &nbsp; (<big>''' ' ' '''</big>) &nbsp; which is within a quoted string (with apostrophes) &nbsp; [in the above and below REXX programming examples].
 
<br>Another test to see if the REXX variable "bloop" exists.
<langsyntaxhighlight lang="rexx">bloop=47
if symbol('bloop')=='VAR' then say 'the "bloop" variable exists.'
else say 'the "bloop" variable doesn''t exist.'</langsyntaxhighlight>
In REXX, the ABS function is a built-in function (BIF).
<langsyntaxhighlight lang="rexx">bloop=47
g=abs(bloop)</langsyntaxhighlight>
However, most REXX interpreters will allow this type of test:
<langsyntaxhighlight lang="rexx">if testxyz() then say 'function XYZ not found.'
else say 'function XYZ was found.'
exit
Line 1,814 ⟶ 2,106:
return 0
/*──────────────────────────────────────────────────────────────────────────────────────*/
syntax: return 1</langsyntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project: Introspection
Line 1,849 ⟶ 2,141:
func abs(bloop)
return fabs(bloop)
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,858 ⟶ 2,150:
Function 'abc' is not defined
</pre>
 
=={{header|RPL}}==
{{works with|HP|49}}
≪ '''IF''' VERSION DROP DUP SIZE DUP 3 - SWAP SUB STR→ 2.15 <
'''THEN''' "Too old RPL version"
'''ELSE'''
'<span style="color:green">BLOOP</span>'
'''IFERR''' RCL
'''THEN''' ": variable not defined" +
'''ELSE'''
ABS
'''IF''' DUP TYPE 6 ==
'''THEN''' ": function not defined" + NIP
'''END'''
'''END'''
'''END'''
≫ '<span style="color:blue">INTROSP</span>' STO
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">exit if RUBY_VERSION < '1.8.6'
puts bloop.abs if defined?(bloop) and bloop.respond_to?(:abs)</langsyntaxhighlight>
 
'''Extra credit:'''
<langsyntaxhighlight lang="ruby">def variable_counter(b)
int_vars = []
sum = 0
Line 1,886 ⟶ 2,195:
a_float = 3.14
 
variable_counter(binding)</langsyntaxhighlight>
 
{{out}}
Line 1,899 ⟶ 2,208:
Note: The warning is because it accessed the global variable which was made invalid.<br>
The meaning of these variables can be found many places, including [http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Variables_and_Constants here].
 
=={{header|Rust}}==
 
Checking for the Rust compiler version can be done using external crates, for example using the rustc_version crate. Simply add the rustc_version dependency into your cargo.toml file under the dependencies:
 
<syntaxhighlight lang="toml">
[dependencies]
rustc_version = "0.4"
</syntaxhighlight>
 
Then we can write code that can check the rust compiler channel, the rust compiler version and check for a minimum version of the rust compiler:
 
<syntaxhighlight lang="rust">
use rustc_version::{version_meta, Channel, version, Version};
 
fn main() {
// We can check the Rust channel currently being used: stable, nightly, etc.
match version_meta().unwrap().channel {
Channel::Stable => {
println!("Rust Stable");
}
Channel::Beta => {
println!("Rust Beta");
}
Channel::Nightly => {
println!("Rust Nightly");
}
Channel::Dev => {
println!("Rust Dev");
}
}
// We can print the Rust compiler version
println!("{}",version().unwrap());
// We can check for a minimum Rust compiler version
if version().unwrap() >= Version::parse("1.50.0").unwrap() {
println!("Rust compiler version is ok.");
} else {
eprintln!("Rust compiler version is too old. Please update to a more recent version.");
std::process::exit(1);
}
}
</syntaxhighlight>
 
When running the code using the stable Rust compiler version 1.71.1 it results in:
 
<pre>
Rust Stable
1.74.1
Rust compiler version is ok.
</pre>
 
There are currently no runtime capabilities built into the Rust compiler for checking whether individual variables or individual functions have been declared. Some crates offer specialized, limited and experimental reflection capabilities; for example for introspecting struct fields we can use the crates introspection or bevy_reflect. Macros and build scripts can also be leveraged as a current workaround for specific and limited scenarios.
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">object VersCheck extends App {
val minimalVersion = 1.7
 
Line 1,909 ⟶ 2,272:
val bloop = Option(-42)
if (bloop.isDefined) bloop.get.abs
}</langsyntaxhighlight>
 
=={{header|Slate}}==
No version string included inside the system presently.
<langsyntaxhighlight lang="slate">Platform run: StartupArguments first ; ' --version'.</langsyntaxhighlight>
 
<langsyntaxhighlight lang="slate">(lobby hasSlotNamed: #bloop) /\ [(#abs findOn: {lobby bloop}) isNotNil] ifTrue: [inform: bloop abs printString].
lobby slotValues inject: 0 into: [| :sum :value | (value is: Integer) ifTrue: [sum + value] ifFalse: [sum]].</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<langsyntaxhighlight lang="smalltalk">| s v t sum hm |
"uncomment the following to see what happens if bloop exists"
"Smalltalk at: #bloop put: -10."
Line 1,956 ⟶ 2,320:
] .
Transcript show: 'Num of global numeric vars: '; show: (hm printString); cr ;
show: 'Sum of global numeric vars: '; show: (sum printString) ; cr.</langsyntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.4 ; # throws an error if older
if {[info exists bloop] && [llength [info functions abs]]} {
puts [expr abs($bloop)]
}</langsyntaxhighlight>
 
'''Extra credit:'''
<langsyntaxhighlight lang="tcl">namespace eval ::extra_credit {
variable sum_global_int 0
variable n_global_int 0
Line 1,978 ⟶ 2,342:
puts "number of global ints = $n_global_int"
puts "their sum = $sum_global_int"
}</langsyntaxhighlight>
 
=={{header|TI-89 BASIC}}==
 
<langsyntaxhighlight lang="ti89b">()
Prgm
Local l, i, vers
Line 2,005 ⟶ 2,369:
© There is no way to get a list of global variables.
EndPrgm</langsyntaxhighlight>
 
=={{header|Toka}}==
Line 2,012 ⟶ 2,376:
Starting with Release 1.1, Toka allows for checking the version number:
 
<langsyntaxhighlight lang="toka">VERSION 101 > [ bye ] ifFalse</langsyntaxhighlight>
 
Release 1.0 can be detected by doing:
 
<langsyntaxhighlight lang="toka">` VERSION FALSE = [ bye ] ifTrue</langsyntaxhighlight>
 
Basic introspection is possible via '''`'''
 
<langsyntaxhighlight lang="toka">` bloop FALSE <> ` abs FALSE <> and [ ` bloop invoke @ ` abs invoke ] ifTrue</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
{{works with|ksh93}}
There's no way to introspect the builtin arithmetic functions. We'll just try it and see if there's an error.
<langsyntaxhighlight lang="bash">case ${.sh.version} in
*93[[:alpha:]]+*) :;; #this appears to be ksh93, we're OK
*) echo "version appears to be too old"
Line 2,046 ⟶ 2,410:
done
print "${int_vars[*]}"
print -- $sum</langsyntaxhighlight>
 
{{works with|bash}}
bash does not have a builtin math function "abs" -- we'll check for a user-defined shell function instead.
<langsyntaxhighlight lang="bash">if [[ $BASH_VERSION < "4.2" ]]; then
echo "version is too old"
exit
Line 2,075 ⟶ 2,439:
echo "${int_vars[*]}"
echo $sum
}</langsyntaxhighlight>
 
=={{header|Ursala}}==
Line 2,100 ⟶ 2,464:
1 by the time it's displayed.
 
<langsyntaxhighlight Ursalalang="ursala">#import std
#import flo
#import lag
Line 2,112 ⟶ 2,476:
#cast %e
 
bloop = -1.</langsyntaxhighlight>
{{out}}
<pre>1.000000e+00</pre>
Line 2,122 ⟶ 2,486:
To determine the version of the environment -- typically meaning which version of Microsoft Office is running -- the <code>Application</code> object has a <code>Version</code> property:
 
<langsyntaxhighlight lang="vb">If Application.Version < 15 Then Exit Sub</langsyntaxhighlight>
 
=={{header|Wren}}==
{{libheader|Wren-pattern}}
{{libheader|Wren-math}}
Note that:
 
* Wren doesn't have reflection as such but is able to obtain and analyze the running script's source code. It is assumed for this purpose that the latter is sensibly formatted - only global declarations are not indented.
* Wren is dynamically typed and has a Num type but not an integer type. As far as the extra credit is concerned, the simplifying assumption has been made that a global variable is an integer if it's assigned an integer literal when it's declared.
<syntaxhighlight lang="wren">import "os" for Platform, Process
import "io" for File
import "meta" for Meta
import "./pattern" for Pattern
import "./math" for Nums
 
var a = 4 /* 1st integer variable */
var b = 0xA /* 2nd integer variable */
var c = -8 /* 3rd integer variable */
 
var bloop = -17.3
 
var checkVersion = Fn.new {
var version = Process.version
var components = version.split(".")
if (Num.fromString(components[1]) < 4) {
Fiber.abort("Wren version (%(version)) is too old.")
}
}
 
var globalIntVars = Fn.new {
var sep = Platform.isWindows ? "\r\n" : "\n"
var lines = File.read(Process.allArguments[1]).split(sep)
var p = Pattern.new("var+1/s[+1/x]+1/s/=+1/s[0x+1/h|~-+1/d]+0/s", Pattern.whole)
var q = Pattern.new("[////|//*]+0/z", Pattern.end)
var vars = []
var vals = []
for (line in lines) {
line = q.replaceAll(line, "") // get rid of any comments
var m = p.find(line)
if (m) {
vars.add(m.capsText[0])
vals.add(Num.fromString(m.capsText[1]))
}
}
return [vars, vals]
}
 
checkVersion.call()
var res = globalIntVars.call()
var d
Meta.eval("d = bloop.abs") // this won't compile if either 'bloop' or 'abs' not available
System.print("bloop.abs = %(d)")
var vars = res[0]
var vals = res[1]
System.print("The sum of the %(vars.count) integer variables, %(vars), is %(Nums.sum(vals))")</syntaxhighlight>
 
{{out}}
<pre>
bloop.abs = 17.3
The sum of the 3 integer variables, [a, b, c], is 6
</pre>
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">if peek("version") < 2.63 error "Interpreter version is too old!"</langsyntaxhighlight>
 
=={{header|Zig}}==
 
'''Works with:''' 0.10.1, 0.11.0, 0.12.0-dev.1577+9ad03b628
 
Note that errors for compiler version check and @hasDecl/@hasField are usually reported at comptime via @compileError, not at runtime, but for demonstrating purposes output is moved to runtime (introspection is still at comptime).
 
<syntaxhighlight lang="zig">const std = @import("std");
const builtin = @import("builtin");
 
pub const bloop: i32 = -1_000;
 
pub fn abs(a: i32) i32 {
return if (a < 0) -a else a;
}
 
pub fn main() error{NotSupported}!void {
if (builtin.zig_version.order(.{ .major = 0, .minor = 11, .patch = 0 }) == .lt) {
std.debug.print("Version {any} is less than 0.11.0, not suitable, exiting!\n", .{builtin.zig_version});
return error.NotSupported;
} else {
std.debug.print("Version {any} is more or equal than 0.11.0, suitable, continuing!\n", .{builtin.zig_version});
}
 
if (@hasDecl(@This(), "bloop") and @hasDecl(@This(), "abs")) {
std.debug.print("abs(bloop) = {d}\n", .{abs(bloop)});
} else {
std.debug.print("abs and/or bloop are not defined!\n", .{});
}
}</syntaxhighlight>
 
{{out|case=Zig version 0.10.1}}
<pre>
Version 0.10.1 is less than 0.11.0, not suitable, exiting!
error: NotSupported
src/instrospection.zig:13:9: 0x211a1e in main (instrospection)
return error.NotSupported;
^
</pre>
 
{{out|case=Zig version 0.11.0}}
<pre>
Version 0.11.0 is more or equal than 0.11.0, suitable, continuing!
abs(bloop) = 1000
</pre>
 
{{out|case=Zig version 0.12.0-dev.1577+9ad03b628}}
<pre>
Version 0.12.0-dev.1577+9ad03b628 is more or equal than 0.11.0, suitable, continuing!
abs(bloop) = 1000
</pre>
 
===Extra credit===
 
<syntaxhighlight lang="zig">const std = @import("std");
 
pub const first_integer_constant: i32 = 5;
pub const second_integer_constant: i32 = 3;
pub const third_integer_constant: i32 = -2;
 
pub const some_non_integer_constant: f32 = 0.0;
pub const another_non_integer_constant: bool = false;
 
pub fn main() void {
comptime var cnt: comptime_int = 0;
comptime var sum: comptime_int = 0;
inline for (@typeInfo(@This()).Struct.decls) |decl_info| {
const decl = @field(@This(), decl_info.name);
switch (@typeInfo(@TypeOf(decl))) {
.Int, .ComptimeInt => {
sum += decl;
cnt += 1;
},
else => continue,
}
}
 
@compileLog(std.fmt.comptimePrint("cnt = {d}, sum = {d}", .{ cnt, sum }));
}</syntaxhighlight>
 
{{out}}
<pre>
src/instrospection.zig:24:5: error: found compile log statement
@compileLog(std.fmt.comptimePrint("cnt = {d}, sum = {d}", .{ cnt, sum }));
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
Compile Log Output:
@as(*const [16:0]u8, "cnt = 3, sum = 6")
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">Language.version //-->L(1,12,8,"2014-04-01")
if (Language.version[1] < 10) System.exit("Too old");
var bloop=-123;
if ((1).resolve("abs",1) and resolve("bloop",8)) bloop.abs().println()</langsyntaxhighlight>
{{out}}<pre>123</pre>
The concept of global vars doesn't really exist, only instance data.
<syntaxhighlight lang="zkl">var n=3, x=1.0, a=5, z="zoo";
self.vars; --> L(L("a",5),L("n",3),L("x",1),L("z","zoo"))
sum:=self.vars.reduce(fcn(p,[(nm,v)],r){
if((1).isType(v)){r.inc();p+v;} else p},0,num:=Ref(0));
println("Num int vars = ",num.value,". Sum = ",sum);</langsyntaxhighlight>
{{out}}<pre>Num int vars = 2. Sum = 8</pre>
 
=={{header|ZX Spectrum Basic}}==
 
<langsyntaxhighlight lang="zxbasic">10 LET totram=PEEK 23732 + 256 * PEEK 23733: REM Check that we have a 48k machine
20 IF totram < 65535 THEN PRINT "Your 16k Spectrum is too old": STOP
30 REM variables must exist before they are used, otherwise we get an error
Line 2,149 ⟶ 2,662:
50 REM I haven't implemented this, because I have forgotten the handler address
60 LET bloob = -4: REM make sure bloob exists, by creating it.
70 PRINT ABS(bloob): REM function will be present, ZX Spectrum Basic is standardized.</langsyntaxhighlight>
 
 
{{omit from|6502 Assembly|(1) depends on the hardware, (2) variable names don't exist at runtime, (3) everything is global scope.}}
{{omit from|68000 Assembly|See 6502 Assembly.}}
{{omit from|8086 Assembly|See 6502 Assembly.}}
{{omit from|GUISS}}
{{omit from|M4}}
{{omit from|M4}}
{{omit from|ML/I}}
{{omit from|Z80 Assembly|See 6502 Assembly.}}
 
[[Category:Initialization]]
490

edits