I am trying to extract all the global variable (eg: float) from a given code:
float aaa = 3.0;
float sat( float t ) {
return clamp( t, 0.0, 1.0 );
}
float bbb = 3.0;
vec3 spectrum_offset( float t ) {
float t0 = 3.0;
return clamp( vec3( -t0, 1.0-abs(t0), t0), 0.0, 1.0);
}
My expect result are:
float aaa = 3.0;
float bbb = 3.0;
I tried with the following regex:
^\s*float\s+.*\s*=\s*.*;
An online example in regexr.com
which gives me the result:
float aaa = 3.0;
float bbb = 3.0;
float t0 = 3.0;
As you can see the last one t0 is inside a function body so this one is the one should not be picked up.
How can I rule out the variable inside any function body leaving only the ones that are in the global area.
Any advice will be appreciated, thanks :)
Whilst this answer doesn't directly use Regular Expressions, I post this as an alternative solution to parsing what looks like GLSL code.
Generally attempting to parse anything considered a programming language using Regular Expressions is a bad plan. This is due to the complexity of the languages i.e. things like comments, variable scope, escaping characters, etc.
It's always best to use a parser built to parse the language. There are generally parsers available for many languages that create an AST.
scope property which contains a list of globals.sat is also considered listed in the scopefloat types.globals variable includes line numbers and position of the globals found.var tokenString = require('glsl-tokenizer/string');
var parseTokens = require('glsl-parser/direct')
const code = `
float aaa = 3.0;
float sat( float t ) {
return clamp( t, 0.0, 1.0 );
}
float bbb = 3.0;
vec3 spectrum_offset( float t ) {
float t0 = 3.0;
return clamp( vec3( -t0, 1.0-abs(t0), t0), 0.0, 1.0);
}
`;
const tokens = tokenString(code);
const ast = parseTokens(tokens)
function filterObject(obj, callback) {
return Object.fromEntries(Object.entries(obj).
filter(([key, val]) => callback(val, key)));
}
const globals = filterObject(ast.scope, x => (
x.parent.type === 'decllist' &&
x.parent.parent.token.data == "float"
));
return globals;
You can view this code running here: https://runkit.com/deanmarktaylor/find-global-variables-in-glsl-code
Here is example output objects, note the line number and position which might be useful.

If you are after doing more than just knowing where the variables are in the code and actually manipulating these found variables...
Instead of manipulating the string of the found global float variables you might find it best use the AST, adjust it and then generate the code from the AST.